|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from collections.abc import Sequence |
| 5 | + |
| 6 | +from django.db.models import Q, QuerySet |
| 7 | +from django.utils import timezone |
| 8 | + |
| 9 | +from sentry.investigations.contracts import ActionRequestItem |
| 10 | +from sentry.investigations.models import ( |
| 11 | + Investigation, |
| 12 | + InvestigationActionRequest, |
| 13 | + InvestigationActionRequestAnchorType, |
| 14 | + InvestigationActionRequestState, |
| 15 | + InvestigationOrchestrationRun, |
| 16 | +) |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +LIVE_STATES = ( |
| 22 | + InvestigationActionRequestState.SUGGESTED, |
| 23 | + InvestigationActionRequestState.FAILED, |
| 24 | +) |
| 25 | + |
| 26 | + |
| 27 | +def _supersede(queryset: QuerySet[InvestigationActionRequest]) -> int: |
| 28 | + return queryset.filter(state__in=LIVE_STATES).update( |
| 29 | + state=InvestigationActionRequestState.SUPERSEDED, date_updated=timezone.now() |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +def supersede_action_requests_before(investigation: Investigation, report_revision: int) -> int: |
| 34 | + """Supersede requests that belonged to an older report. |
| 35 | +
|
| 36 | + Only the primary and block-anchored requests go away with the old report. A re-run can |
| 37 | + ask for hypothesis and unanchored requests before its new report starts, so we keep |
| 38 | + those until Seer re-sends, withdraws, or leaves them out of a snapshot. |
| 39 | + """ |
| 40 | + |
| 41 | + return _supersede( |
| 42 | + InvestigationActionRequest.objects.filter( |
| 43 | + investigation=investigation, report_revision__lt=report_revision |
| 44 | + ).filter(Q(primary=True) | Q(anchor_type=InvestigationActionRequestAnchorType.BLOCK)) |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def _replace_primary(investigation: Investigation, row: InvestigationActionRequest) -> None: |
| 49 | + """Make `row` the only live primary. |
| 50 | +
|
| 51 | + An older primary with an anchor stays as a normal request under that anchor. One without |
| 52 | + an anchor is superseded. |
| 53 | + """ |
| 54 | + |
| 55 | + others = InvestigationActionRequest.objects.filter( |
| 56 | + investigation=investigation, primary=True, state__in=LIVE_STATES |
| 57 | + ).exclude(id=row.id) |
| 58 | + others.filter(anchor_type__isnull=False).update(primary=False, date_updated=timezone.now()) |
| 59 | + _supersede(others.filter(anchor_type__isnull=True)) |
| 60 | + |
| 61 | + |
| 62 | +def upsert_action_request( |
| 63 | + run: InvestigationOrchestrationRun, item: ActionRequestItem, *, replace_primary: bool = True |
| 64 | +) -> InvestigationActionRequest: |
| 65 | + """Create or update the request with this key. Callers must hold the investigation and |
| 66 | + run locks. |
| 67 | +
|
| 68 | + Applied requests are never touched. Failed, withdrawn, or errored requests only come back |
| 69 | + if Seer changes the action, so replaying an event can't bring them back. |
| 70 | + """ |
| 71 | + |
| 72 | + investigation = run.investigation |
| 73 | + anchor = item["anchor"] |
| 74 | + action = item["action"] |
| 75 | + display: dict[str, object] = { |
| 76 | + "report_revision": item["reportRevision"], |
| 77 | + "primary": item["primary"], |
| 78 | + "anchor_type": anchor["type"] if anchor else None, |
| 79 | + "anchor_id": anchor["id"] if anchor else None, |
| 80 | + "title": item["title"], |
| 81 | + "rationale": item["rationale"], |
| 82 | + "impact": item["impact"], |
| 83 | + } |
| 84 | + row = InvestigationActionRequest.objects.filter( |
| 85 | + investigation=investigation, key=item["key"] |
| 86 | + ).first() |
| 87 | + if row is None: |
| 88 | + row = InvestigationActionRequest.objects.create( |
| 89 | + investigation=investigation, |
| 90 | + key=item["key"], |
| 91 | + action_kind=action["kind"] if action is not None else None, |
| 92 | + action_payload=action, |
| 93 | + **display, |
| 94 | + ) |
| 95 | + elif row.state != InvestigationActionRequestState.APPLIED: |
| 96 | + update_fields = [*display, "date_updated"] |
| 97 | + for field, value in display.items(): |
| 98 | + setattr(row, field, value) |
| 99 | + if row.action_payload != action: |
| 100 | + row.action_kind = action["kind"] if action is not None else None |
| 101 | + row.action_payload = action |
| 102 | + row.state = InvestigationActionRequestState.SUGGESTED |
| 103 | + row.error = None |
| 104 | + row.reason = None |
| 105 | + update_fields.extend(["action_kind", "action_payload", "state", "error", "reason"]) |
| 106 | + elif row.state == InvestigationActionRequestState.SUPERSEDED and row.error is None: |
| 107 | + row.state = InvestigationActionRequestState.SUGGESTED |
| 108 | + update_fields.append("state") |
| 109 | + row.save(update_fields=update_fields) |
| 110 | + |
| 111 | + if item["primary"]: |
| 112 | + if row.state not in LIVE_STATES: |
| 113 | + # Seer should have used a new key. A finished request can't be the next step again. |
| 114 | + logger.warning( |
| 115 | + "investigations.action_requests.terminal_key_reused", |
| 116 | + extra={"action_request_id": row.id, "state": row.state}, |
| 117 | + ) |
| 118 | + if replace_primary: |
| 119 | + _replace_primary(investigation, row) |
| 120 | + return row |
| 121 | + |
| 122 | + |
| 123 | +def withdraw_action_request(run: InvestigationOrchestrationRun, key: str, reason: str) -> bool: |
| 124 | + """Withdraw a suggested request that Seer no longer stands behind. Applied and failed |
| 125 | + requests are left alone. |
| 126 | + """ |
| 127 | + |
| 128 | + return bool( |
| 129 | + InvestigationActionRequest.objects.filter( |
| 130 | + investigation=run.investigation, |
| 131 | + key=key, |
| 132 | + state=InvestigationActionRequestState.SUGGESTED, |
| 133 | + ).update( |
| 134 | + state=InvestigationActionRequestState.WITHDRAWN, |
| 135 | + reason=reason, |
| 136 | + date_updated=timezone.now(), |
| 137 | + ) |
| 138 | + ) |
| 139 | + |
| 140 | + |
| 141 | +def sync_snapshot_action_requests( |
| 142 | + run: InvestigationOrchestrationRun, items: Sequence[ActionRequestItem] |
| 143 | +) -> None: |
| 144 | + """Treat the snapshot as the full list: any live request it leaves out is superseded.""" |
| 145 | + |
| 146 | + primaries: list[InvestigationActionRequest] = [] |
| 147 | + for item in items: |
| 148 | + row = upsert_action_request(run, item, replace_primary=False) |
| 149 | + if item["primary"]: |
| 150 | + primaries.append(row) |
| 151 | + if primaries: |
| 152 | + # Pick the newest revision, then a suggested request over a failed one, then the key, |
| 153 | + # so the list order never decides which primary wins. |
| 154 | + _replace_primary( |
| 155 | + run.investigation, |
| 156 | + max( |
| 157 | + primaries, |
| 158 | + key=lambda row: ( |
| 159 | + row.report_revision, |
| 160 | + row.state == InvestigationActionRequestState.SUGGESTED, |
| 161 | + row.key, |
| 162 | + ), |
| 163 | + ), |
| 164 | + ) |
| 165 | + _supersede( |
| 166 | + InvestigationActionRequest.objects.filter(investigation=run.investigation).exclude( |
| 167 | + key__in=[item["key"] for item in items] |
| 168 | + ) |
| 169 | + ) |
| 170 | + |
| 171 | + |
| 172 | +def supersede_block_action_requests(investigation: Investigation, block_keys: Sequence[str]) -> int: |
| 173 | + """Supersede the requests anchored to blocks that were just removed, since their anchor is |
| 174 | + gone and the UI would have nowhere to show them. |
| 175 | + """ |
| 176 | + |
| 177 | + return _supersede( |
| 178 | + InvestigationActionRequest.objects.filter( |
| 179 | + investigation=investigation, |
| 180 | + anchor_type=InvestigationActionRequestAnchorType.BLOCK, |
| 181 | + anchor_id__in=block_keys, |
| 182 | + ) |
| 183 | + ) |
0 commit comments