gooddata-eval 1.80.1.dev10__py3-none-any.whl → 1.80.1.dev12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gooddata_eval/core/agentic/_alert_update.py +567 -0
- gooddata_eval/core/agentic/_catalog.py +19 -21
- gooddata_eval/core/agentic/_metric_workspace.py +23 -13
- gooddata_eval/core/agentic/alert_skill.py +951 -69
- gooddata_eval/core/agentic/metric_skill.py +153 -6
- gooddata_eval/core/chat/sse_client.py +40 -9
- gooddata_eval/core/evaluators/_deep_subset.py +15 -2
- {gooddata_eval-1.80.1.dev10.dist-info → gooddata_eval-1.80.1.dev12.dist-info}/METADATA +68 -2
- {gooddata_eval-1.80.1.dev10.dist-info → gooddata_eval-1.80.1.dev12.dist-info}/RECORD +12 -11
- {gooddata_eval-1.80.1.dev10.dist-info → gooddata_eval-1.80.1.dev12.dist-info}/WHEEL +0 -0
- {gooddata_eval-1.80.1.dev10.dist-info → gooddata_eval-1.80.1.dev12.dist-info}/entry_points.txt +0 -0
- {gooddata_eval-1.80.1.dev10.dist-info → gooddata_eval-1.80.1.dev12.dist-info}/licenses/LICENSE.txt +0 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
# (C) 2026 GoodData Corporation. All rights reserved.
|
|
2
|
+
"""Update mode of the agentic alert-skill evaluation: the agent changes an alert that exists before the question.
|
|
3
|
+
|
|
4
|
+
An item in this mode states the alert to set up and the change its question asks for. Each run creates the
|
|
5
|
+
alert through the API, asks the question, and compares the stored alert before and after. The asked fields
|
|
6
|
+
must hold the new values, and every other field must be unchanged. ``update_metric_alert`` keeps every field
|
|
7
|
+
it is not given, so its arguments cannot show a field the update lost on the way. Only the stored alert can.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import uuid
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, ClassVar
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
# Score names, in report order. An update item publishes these and none of the creation checks.
|
|
22
|
+
UPDATE_CHECKS = ("alert_update_called", "alert_update_correct", "alert_update_preserved", "alert_not_recreated")
|
|
23
|
+
# Tools that change an existing alert: the condition and settings, and the paused/active state.
|
|
24
|
+
UPDATE_TOOLS = ("update_metric_alert", "update_alert_state")
|
|
25
|
+
|
|
26
|
+
_MODE_UPDATE = "update"
|
|
27
|
+
_PAGE_SIZE = 250
|
|
28
|
+
# Keys under which an AFM attribute filter lists the elements it selects (`in`/`notIn`).
|
|
29
|
+
_ELEMENT_KEYS = ("values", "uris")
|
|
30
|
+
# Every setup alert's id starts with this, so a run deletes only alerts an earlier run left.
|
|
31
|
+
SETUP_ID_PREFIX = "eval-update-"
|
|
32
|
+
_ITEM_KEYS = ("mode", "setup_alert", "expected_change")
|
|
33
|
+
|
|
34
|
+
_ALERT = ("attributes", "alert")
|
|
35
|
+
# Server bookkeeping that every write changes, and the text gen-ai generates from the condition when it
|
|
36
|
+
# creates the alert. A correct update may rewrite that text, so it is not compared.
|
|
37
|
+
_IGNORED_PATHS = (
|
|
38
|
+
("attributes", "createdAt"),
|
|
39
|
+
("attributes", "modifiedAt"),
|
|
40
|
+
("attributes", "description"),
|
|
41
|
+
("relationships", "createdBy"),
|
|
42
|
+
("relationships", "modifiedBy"),
|
|
43
|
+
("relationships", "automationResults"),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_COMPARISON_OPERATORS = (
|
|
47
|
+
"GREATER_THAN",
|
|
48
|
+
"GREATER_THAN_OR_EQUAL_TO",
|
|
49
|
+
"LESS_THAN",
|
|
50
|
+
"LESS_THAN_OR_EQUAL_TO",
|
|
51
|
+
"EQUAL_TO",
|
|
52
|
+
"NOT_EQUAL_TO",
|
|
53
|
+
)
|
|
54
|
+
_RELATIVE_OPERATORS = ("INCREASES_BY", "DECREASES_BY", "CHANGES_BY")
|
|
55
|
+
_TRIGGERS = ("ALWAYS", "ONCE", "ONCE_PER_INTERVAL")
|
|
56
|
+
_TRIGGER_DISPLAY = {"EVERY TIME": "ALWAYS", "ONE TIME": "ONCE"}
|
|
57
|
+
_TRIGGER_INTERVALS = ("DAY", "WEEK", "MONTH", "QUARTER", "YEAR")
|
|
58
|
+
_SENSITIVITIES = ("LOW", "MEDIUM", "HIGH")
|
|
59
|
+
_GRANULARITIES = ("HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR")
|
|
60
|
+
_STATES = ("ACTIVE", "PAUSED")
|
|
61
|
+
_CONDITION_KINDS = ("comparison", "relative", "anomaly", "range")
|
|
62
|
+
_ENUMS: dict[str, tuple[str, ...]] = {
|
|
63
|
+
"trigger": _TRIGGERS,
|
|
64
|
+
"trigger_interval": _TRIGGER_INTERVALS,
|
|
65
|
+
"sensitivity": _SENSITIVITIES,
|
|
66
|
+
"granularity": _GRANULARITIES,
|
|
67
|
+
"state": _STATES,
|
|
68
|
+
}
|
|
69
|
+
# The condition kinds each change applies to; a change missing here applies to every kind.
|
|
70
|
+
_KINDS_OF_CHANGE = {
|
|
71
|
+
"threshold": ("comparison", "relative"),
|
|
72
|
+
"operator": ("comparison", "relative"),
|
|
73
|
+
"sensitivity": ("anomaly",),
|
|
74
|
+
"granularity": ("anomaly",),
|
|
75
|
+
}
|
|
76
|
+
_CHANGE_ALIASES = {"dashboard": "dashboard_id", "interval": "trigger_interval", "name": "title"}
|
|
77
|
+
_CHANGES = ("threshold", "operator", "trigger", "trigger_interval", "sensitivity", "granularity", "title", "state")
|
|
78
|
+
_CHANGES_WITH_SHAPE = ("filters", "dashboard_id")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class AlertUpdateExpectation:
|
|
83
|
+
"""The alert a run sets up and the change its question asks for."""
|
|
84
|
+
|
|
85
|
+
setup_alert: dict[str, Any]
|
|
86
|
+
"""The automation entity to create: ``attributes`` and optional ``relationships``, as the API returns them."""
|
|
87
|
+
expected_change: dict[str, Any]
|
|
88
|
+
"""New value per changed field, by canonical name (``threshold``, ``trigger``, ``filters``, ...)."""
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def title(self) -> str:
|
|
92
|
+
return self.setup_alert["attributes"]["title"]
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def condition_kind(self) -> str:
|
|
96
|
+
return condition_kind(self.setup_alert)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class AlertUpdateEvaluation:
|
|
101
|
+
"""Scores of one update run."""
|
|
102
|
+
|
|
103
|
+
alert_update_called: bool
|
|
104
|
+
"""An update tool call on the setup alert succeeded."""
|
|
105
|
+
alert_update_correct: bool
|
|
106
|
+
"""The stored alert holds every value the item expects to change."""
|
|
107
|
+
alert_update_preserved: bool
|
|
108
|
+
"""No other field of the stored alert changed."""
|
|
109
|
+
alert_not_recreated: bool
|
|
110
|
+
"""The setup alert still exists and the agent created no alert."""
|
|
111
|
+
|
|
112
|
+
# The check every other one depends on: without an update call, the others read False.
|
|
113
|
+
prerequisite: ClassVar[str] = "alert_update_called"
|
|
114
|
+
|
|
115
|
+
def checks(self) -> dict[str, bool]:
|
|
116
|
+
return {name: getattr(self, name) for name in UPDATE_CHECKS}
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def strict_pass(self) -> bool:
|
|
120
|
+
return all(self.checks().values())
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _canonical(key: object) -> str:
|
|
124
|
+
return str(key).strip().lower().replace(" ", "_")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _get(d: dict, *keys: str) -> Any:
|
|
128
|
+
"""A value by any of ``keys``, case-insensitively; spaces and underscores are interchangeable."""
|
|
129
|
+
by_name = {_canonical(k): v for k, v in d.items()}
|
|
130
|
+
for key in keys:
|
|
131
|
+
if key in by_name:
|
|
132
|
+
return by_name[key]
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def condition_kind(entity: dict) -> str:
|
|
137
|
+
"""``comparison``, ``relative``, ``anomaly`` or ``range``: the one key of the alert condition."""
|
|
138
|
+
condition = ((entity.get("attributes") or {}).get("alert") or {}).get("condition")
|
|
139
|
+
bodies = {k: v for k, v in condition.items() if v is not None} if isinstance(condition, dict) else {}
|
|
140
|
+
if len(bodies) != 1:
|
|
141
|
+
raise ValueError(f"setup_alert must have exactly one alert condition, got {list(bodies)}")
|
|
142
|
+
[(kind, body)] = bodies.items()
|
|
143
|
+
if kind not in _CONDITION_KINDS:
|
|
144
|
+
raise ValueError(f"setup_alert condition must be one of {list(_CONDITION_KINDS)}, got {kind!r}")
|
|
145
|
+
if not isinstance(body, dict):
|
|
146
|
+
raise ValueError(f"setup_alert condition {kind} must be an object, got {body!r}")
|
|
147
|
+
return kind
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _normalize_setup_alert(value: object) -> dict[str, Any]:
|
|
151
|
+
if not isinstance(value, dict):
|
|
152
|
+
raise ValueError(f"setup_alert must be an automation entity object, got {value!r}")
|
|
153
|
+
unknown = sorted(set(value) - {"attributes", "relationships", "id", "type"})
|
|
154
|
+
if unknown:
|
|
155
|
+
raise ValueError(f"setup_alert takes only attributes and relationships, got {unknown}")
|
|
156
|
+
attributes = value.get("attributes")
|
|
157
|
+
if not isinstance(attributes, dict) or not isinstance(attributes.get("alert"), dict):
|
|
158
|
+
raise ValueError("setup_alert.attributes.alert is required")
|
|
159
|
+
title = attributes.get("title")
|
|
160
|
+
if not isinstance(title, str) or not title.strip():
|
|
161
|
+
# The agent finds the alert by its title, and each run deletes alerts with the same title first.
|
|
162
|
+
raise ValueError("setup_alert.attributes.title is required: it identifies the alert to the agent")
|
|
163
|
+
relationships = value.get("relationships")
|
|
164
|
+
relationships = {} if relationships is None else relationships
|
|
165
|
+
if not isinstance(relationships, dict):
|
|
166
|
+
raise ValueError(f"setup_alert.relationships must be an object, got {relationships!r}")
|
|
167
|
+
entity = {"attributes": copy.deepcopy(attributes), "relationships": copy.deepcopy(relationships)}
|
|
168
|
+
for section, key in _IGNORED_PATHS:
|
|
169
|
+
if key != "description":
|
|
170
|
+
entity[section].pop(key, None)
|
|
171
|
+
condition_kind(entity)
|
|
172
|
+
return entity
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _finite(value: float) -> bool:
|
|
176
|
+
"""Whether the scorer can compare ``value`` as a float: not NaN, not infinite, not too large."""
|
|
177
|
+
try:
|
|
178
|
+
return math.isfinite(float(value))
|
|
179
|
+
except OverflowError:
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _normalize_change(key: str, value: object, kind: str) -> object:
|
|
184
|
+
kinds = _KINDS_OF_CHANGE.get(key)
|
|
185
|
+
if kinds is not None and kind not in kinds:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
f"expected_change.{key} applies only to {' and '.join(kinds)} alerts, the setup alert is {kind}"
|
|
188
|
+
)
|
|
189
|
+
if key == "threshold":
|
|
190
|
+
if isinstance(value, bool) or not isinstance(value, int | float) or not _finite(value):
|
|
191
|
+
raise ValueError(f"expected_change.threshold must be a finite number, got {value!r}")
|
|
192
|
+
return value
|
|
193
|
+
if key == "operator":
|
|
194
|
+
operators = _COMPARISON_OPERATORS if kind == "comparison" else _RELATIVE_OPERATORS
|
|
195
|
+
canonical = str(value).strip().upper()
|
|
196
|
+
if canonical not in operators:
|
|
197
|
+
raise ValueError(f"expected_change.operator must be one of {list(operators)}, got {value!r}")
|
|
198
|
+
return canonical
|
|
199
|
+
if key in _ENUMS:
|
|
200
|
+
canonical = str(value).strip().upper()
|
|
201
|
+
canonical = _TRIGGER_DISPLAY.get(canonical, canonical) if key == "trigger" else canonical
|
|
202
|
+
if canonical not in _ENUMS[key]:
|
|
203
|
+
raise ValueError(f"expected_change.{key} must be one of {list(_ENUMS[key])}, got {value!r}")
|
|
204
|
+
return canonical
|
|
205
|
+
if key == "filters":
|
|
206
|
+
# An empty object would fit any stored filter; `[]` (no filter at all) stays valid.
|
|
207
|
+
if not isinstance(value, list) or not all(isinstance(f, dict) and f for f in value):
|
|
208
|
+
raise ValueError(f"expected_change.filters must be a list of non-empty filter objects, got {value!r}")
|
|
209
|
+
return value
|
|
210
|
+
if not isinstance(value, str) or not value.strip():
|
|
211
|
+
raise ValueError(f"expected_change.{key} must be a non-empty string, got {value!r}")
|
|
212
|
+
return value
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def update_expectation(expected: dict) -> AlertUpdateExpectation | None:
|
|
216
|
+
"""The update expectation of an item in update mode; None only when ``expected`` has no ``mode`` key.
|
|
217
|
+
|
|
218
|
+
Raises on a malformed item, so a typo never reads green: a ``mode`` other than ``update`` (null
|
|
219
|
+
included), an unknown key, a change the setup alert cannot take, or a trigger interval without the
|
|
220
|
+
ONCE_PER_INTERVAL trigger.
|
|
221
|
+
"""
|
|
222
|
+
# Only an item without the key is a creation item: `mode: null` next to update keys is a typo.
|
|
223
|
+
if "mode" not in {_canonical(k) for k in expected}:
|
|
224
|
+
return None
|
|
225
|
+
mode = _get(expected, "mode")
|
|
226
|
+
if not isinstance(mode, str) or mode.strip().lower() != _MODE_UPDATE:
|
|
227
|
+
raise ValueError(f"mode must be {_MODE_UPDATE!r}, got {mode!r}")
|
|
228
|
+
unknown = sorted(k for k in expected if _canonical(k) not in _ITEM_KEYS)
|
|
229
|
+
if unknown:
|
|
230
|
+
# A creation key next to update mode would be ignored, and the item would read green without it.
|
|
231
|
+
raise ValueError(f"an update item takes only {list(_ITEM_KEYS)}, got also {unknown}")
|
|
232
|
+
setup = _normalize_setup_alert(_get(expected, "setup_alert"))
|
|
233
|
+
kind = condition_kind(setup)
|
|
234
|
+
raw_change = _get(expected, "expected_change")
|
|
235
|
+
if not isinstance(raw_change, dict) or not raw_change:
|
|
236
|
+
raise ValueError(f"expected_change must name at least one field, got {raw_change!r}")
|
|
237
|
+
change: dict[str, Any] = {}
|
|
238
|
+
for raw_key, value in raw_change.items():
|
|
239
|
+
key = _CHANGE_ALIASES.get(_canonical(raw_key), _canonical(raw_key))
|
|
240
|
+
if key not in _CHANGES + _CHANGES_WITH_SHAPE:
|
|
241
|
+
raise ValueError(
|
|
242
|
+
f"expected_change.{raw_key} is not a field update mode checks; use one of "
|
|
243
|
+
f"{list(_CHANGES + _CHANGES_WITH_SHAPE)}"
|
|
244
|
+
)
|
|
245
|
+
if key in change:
|
|
246
|
+
raise ValueError(f"expected_change names {key} twice, the second time as {raw_key!r}")
|
|
247
|
+
change[key] = _normalize_change(key, value, kind)
|
|
248
|
+
if "trigger_interval" in change:
|
|
249
|
+
trigger = change.get("trigger", (setup["attributes"]["alert"].get("trigger") or "").upper())
|
|
250
|
+
if trigger != "ONCE_PER_INTERVAL":
|
|
251
|
+
raise ValueError(f"expected_change.trigger_interval needs the ONCE_PER_INTERVAL trigger, got {trigger!r}")
|
|
252
|
+
return AlertUpdateExpectation(setup_alert=setup, expected_change=change)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def setup_entity(expectation: AlertUpdateExpectation, *, current_user_id: str, channel_id: str | None) -> dict:
|
|
256
|
+
"""The entity a run creates: the item's setup alert, sent to the current user over the org's channel.
|
|
257
|
+
|
|
258
|
+
An item states neither, so that it runs in any organization: the token owner differs per environment,
|
|
259
|
+
and so do the notification channel ids.
|
|
260
|
+
"""
|
|
261
|
+
entity = copy.deepcopy(expectation.setup_alert)
|
|
262
|
+
relationships = entity["relationships"]
|
|
263
|
+
relationships.setdefault("recipients", {"data": [{"id": current_user_id, "type": "user"}]})
|
|
264
|
+
if "notificationChannel" not in relationships and channel_id is not None:
|
|
265
|
+
relationships["notificationChannel"] = {"data": {"id": channel_id, "type": "notificationChannel"}}
|
|
266
|
+
return entity
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def needs_channel(expectation: AlertUpdateExpectation) -> bool:
|
|
270
|
+
return "notificationChannel" not in expectation.setup_alert["relationships"]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _owned_paths(key: str, kind: str, *, keeps_interval: bool = False) -> tuple[tuple[str, ...], ...]:
|
|
274
|
+
"""The stored paths a change of ``key`` may rewrite; a difference under any other path is a lost field.
|
|
275
|
+
|
|
276
|
+
``keeps_interval``: the trigger stays ONCE_PER_INTERVAL, so a trigger change must leave the interval as it is.
|
|
277
|
+
"""
|
|
278
|
+
condition = (*_ALERT, "condition", kind)
|
|
279
|
+
owned: dict[str, tuple[tuple[str, ...], ...]] = {
|
|
280
|
+
"threshold": ((*condition, "right", "value"),) if kind == "comparison" else ((*condition, "threshold"),),
|
|
281
|
+
"operator": ((*condition, "operator"),),
|
|
282
|
+
# Leaving ONCE_PER_INTERVAL clears the interval, and entering it sets one.
|
|
283
|
+
"trigger": ((*_ALERT, "trigger"),) if keeps_interval else ((*_ALERT, "trigger"), (*_ALERT, "interval")),
|
|
284
|
+
"trigger_interval": ((*_ALERT, "interval"),),
|
|
285
|
+
"sensitivity": ((*condition, "sensitivity"),),
|
|
286
|
+
"granularity": ((*condition, "granularity"),),
|
|
287
|
+
"title": (("attributes", "title"),),
|
|
288
|
+
"state": (("attributes", "state"),),
|
|
289
|
+
# The filter list, the dashboard dialog's record of which filters it shows and hides, and the labels
|
|
290
|
+
# they use. The rest of the metadata, such as the widget the alert was set on, is not the change's.
|
|
291
|
+
"filters": (
|
|
292
|
+
(*_ALERT, "execution", "filters"),
|
|
293
|
+
("attributes", "metadata", "filters"),
|
|
294
|
+
("attributes", "metadata", "visibleFilters"),
|
|
295
|
+
("relationships", "labels"),
|
|
296
|
+
),
|
|
297
|
+
"dashboard_id": (("relationships", "analyticalDashboard"),),
|
|
298
|
+
}
|
|
299
|
+
return owned[key]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _at(entity: dict, path: tuple[str, ...]) -> Any:
|
|
303
|
+
node: Any = entity
|
|
304
|
+
for key in path:
|
|
305
|
+
if not isinstance(node, dict):
|
|
306
|
+
return None
|
|
307
|
+
node = node.get(key)
|
|
308
|
+
return node
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _stored_value(entity: dict, key: str, kind: str) -> Any:
|
|
312
|
+
if key == "dashboard_id":
|
|
313
|
+
return _at(entity, ("relationships", "analyticalDashboard", "data", "id"))
|
|
314
|
+
if key == "threshold" and kind == "relative":
|
|
315
|
+
return _at(entity, (*_ALERT, "condition", kind, "threshold", "value"))
|
|
316
|
+
return _at(entity, _owned_paths(key, kind)[0])
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _contains(expected: object, actual: object) -> bool:
|
|
320
|
+
"""Whether ``expected`` is a recursive subset of ``actual``: a filter may carry ids the item omits."""
|
|
321
|
+
if isinstance(expected, dict) and isinstance(actual, dict):
|
|
322
|
+
return all(k in actual and _contains_value(k, v, actual[k]) for k, v in expected.items())
|
|
323
|
+
if isinstance(expected, list) and isinstance(actual, list):
|
|
324
|
+
return len(expected) == len(actual) and all(_contains(e, a) for e, a in zip(expected, actual))
|
|
325
|
+
return expected == actual
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _same_filters(expected: list, actual: object) -> bool:
|
|
329
|
+
"""The same filters in any order; each stored filter may add a localIdentifier and defaults.
|
|
330
|
+
|
|
331
|
+
One expected filter can fit several stored ones, so every pairing is tried, not the first fit.
|
|
332
|
+
"""
|
|
333
|
+
if not isinstance(actual, list) or len(actual) != len(expected):
|
|
334
|
+
return False
|
|
335
|
+
fits = [[i for i, got in enumerate(actual) if _contains(want, got)] for want in expected]
|
|
336
|
+
owner: dict[int, int] = {}
|
|
337
|
+
return all(_assign(fits, want, owner, set()) for want in range(len(fits)))
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _assign(fits: list[list[int]], want: int, owner: dict[int, int], visited: set[int]) -> bool:
|
|
341
|
+
"""Give expected filter ``want`` a stored filter, moving earlier owners along an augmenting path."""
|
|
342
|
+
for got in fits[want]:
|
|
343
|
+
if got in visited:
|
|
344
|
+
continue
|
|
345
|
+
visited.add(got)
|
|
346
|
+
if got not in owner or _assign(fits, owner[got], owner, visited):
|
|
347
|
+
owner[got] = want
|
|
348
|
+
return True
|
|
349
|
+
return False
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _change_applied(key: str, expected: Any, stored: Any) -> bool:
|
|
353
|
+
if key == "threshold":
|
|
354
|
+
return (
|
|
355
|
+
isinstance(stored, int | float)
|
|
356
|
+
and not isinstance(stored, bool)
|
|
357
|
+
and math.isclose(float(stored), float(expected), rel_tol=1e-9, abs_tol=1e-12)
|
|
358
|
+
)
|
|
359
|
+
if key == "filters":
|
|
360
|
+
return _same_filters(expected, stored)
|
|
361
|
+
return stored == expected
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _ignored(path: tuple[str, ...], owned: list[tuple[str, ...]]) -> bool:
|
|
365
|
+
return any(path[: len(prefix)] == prefix for prefix in [*_IGNORED_PATHS, *owned])
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _contains_value(key: str, expected: object, actual: object) -> bool:
|
|
369
|
+
# The elements an attribute filter selects are a set: the agent may list them in another order.
|
|
370
|
+
if key in _ELEMENT_KEYS and isinstance(expected, list) and isinstance(actual, list):
|
|
371
|
+
return sorted(map(json.dumps, expected)) == sorted(map(json.dumps, actual))
|
|
372
|
+
return _contains(expected, actual)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _differences(before: object, after: object, path: tuple[str, ...], out: list[dict]) -> None:
|
|
376
|
+
# An object that appears or disappears is compared field by field, so an owned child such as
|
|
377
|
+
# metadata.visibleFilters can be added to an alert that had no metadata.
|
|
378
|
+
if isinstance(before, dict) and after is None:
|
|
379
|
+
after = {}
|
|
380
|
+
elif before is None and isinstance(after, dict):
|
|
381
|
+
before = {}
|
|
382
|
+
if isinstance(before, dict) and isinstance(after, dict):
|
|
383
|
+
for key in sorted(set(before) | set(after)):
|
|
384
|
+
_differences(before.get(key), after.get(key), (*path, key), out)
|
|
385
|
+
elif before != after:
|
|
386
|
+
# A missing key and a null read the same: the API omits some nulls on one write and not another.
|
|
387
|
+
out.append({"path": ".".join(path), "before": before, "after": after})
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def unexpected_changes(expectation: AlertUpdateExpectation, before: dict, after: dict) -> list[dict]:
|
|
391
|
+
"""Every stored field that changed although the item did not ask for it, as ``{path, before, after}``."""
|
|
392
|
+
kind = condition_kind(before)
|
|
393
|
+
change = expectation.expected_change
|
|
394
|
+
keeps_interval = change.get("trigger") == _at(before, (*_ALERT, "trigger")) == "ONCE_PER_INTERVAL"
|
|
395
|
+
owned = [path for key in change for path in _owned_paths(key, kind, keeps_interval=keeps_interval)]
|
|
396
|
+
diffs: list[dict] = []
|
|
397
|
+
_differences(before, after, (), diffs)
|
|
398
|
+
return [d for d in diffs if not _ignored(tuple(d["path"].split(".")), owned)]
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def evaluate_update(
|
|
402
|
+
expectation: AlertUpdateExpectation,
|
|
403
|
+
*,
|
|
404
|
+
before: dict,
|
|
405
|
+
after: dict | None,
|
|
406
|
+
update_called: bool,
|
|
407
|
+
alert_created: bool,
|
|
408
|
+
) -> tuple[AlertUpdateEvaluation, list[dict]]:
|
|
409
|
+
"""Score one run from the stored alert before the question and after it; also returns the unexpected changes.
|
|
410
|
+
|
|
411
|
+
``after`` is None when the alert no longer exists: the agent deleted it, or deleted and recreated it.
|
|
412
|
+
"""
|
|
413
|
+
if after is None:
|
|
414
|
+
evaluation = AlertUpdateEvaluation(
|
|
415
|
+
alert_update_called=update_called,
|
|
416
|
+
alert_update_correct=False,
|
|
417
|
+
alert_update_preserved=False,
|
|
418
|
+
alert_not_recreated=False,
|
|
419
|
+
)
|
|
420
|
+
return evaluation, []
|
|
421
|
+
kind = condition_kind(before)
|
|
422
|
+
applied = all(
|
|
423
|
+
_change_applied(key, value, _stored_value(after, key, kind))
|
|
424
|
+
for key, value in expectation.expected_change.items()
|
|
425
|
+
)
|
|
426
|
+
changes = unexpected_changes(expectation, before, after)
|
|
427
|
+
evaluation = AlertUpdateEvaluation(
|
|
428
|
+
alert_update_called=update_called,
|
|
429
|
+
alert_update_correct=update_called and applied,
|
|
430
|
+
alert_update_preserved=update_called and not changes,
|
|
431
|
+
alert_not_recreated=not alert_created,
|
|
432
|
+
)
|
|
433
|
+
return evaluation, changes
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def targets_alert(args: dict, alert_id: str) -> bool:
|
|
437
|
+
"""Whether an update call names ``alert_id``: ``automation_id``, or ``automation_ids``.
|
|
438
|
+
|
|
439
|
+
``automation_ids`` is a list, one id, or a list encoded as a JSON string, which the tool also accepts.
|
|
440
|
+
"""
|
|
441
|
+
if args.get("automation_id") == alert_id:
|
|
442
|
+
return True
|
|
443
|
+
ids = args.get("automation_ids")
|
|
444
|
+
if isinstance(ids, str) and ids.strip().startswith("["):
|
|
445
|
+
try:
|
|
446
|
+
ids = json.loads(ids)
|
|
447
|
+
except json.JSONDecodeError:
|
|
448
|
+
return False
|
|
449
|
+
return ids == alert_id or (isinstance(ids, list) and alert_id in ids)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def update_sim_user_prompt(question: str, title: str) -> str:
|
|
453
|
+
"""The simulated user of an update item: it confirms the requested change and nothing else."""
|
|
454
|
+
return (
|
|
455
|
+
"You are a user who asked an AI agent to change one of your existing alerts.\n"
|
|
456
|
+
f'Your request was: "{question}"\n'
|
|
457
|
+
f'The alert is the one titled "{title}".\n'
|
|
458
|
+
"Rules you MUST follow:\n"
|
|
459
|
+
"1. Your goal is exactly the change in your request. Never ask for any other change.\n"
|
|
460
|
+
"2. If the agent asks you to confirm that change, or shows a summary or proposal of it, confirm: "
|
|
461
|
+
"'Yes, please apply that change.'\n"
|
|
462
|
+
f'3. If the agent asks which alert you mean, it is the one titled "{title}".\n'
|
|
463
|
+
"4. If the agent proposes to change anything else, to create a new alert or to delete this one, "
|
|
464
|
+
"decline and repeat your request.\n"
|
|
465
|
+
"5. If the agent asks about a setting your request does not mention, tell it to keep the current value.\n"
|
|
466
|
+
"Reply concisely and directly."
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
class AutomationApi:
|
|
471
|
+
"""The workspace automation entities one update run creates, reads and deletes."""
|
|
472
|
+
|
|
473
|
+
def __init__(
|
|
474
|
+
self, host: str, token: str, workspace_id: str, *, transport: httpx.BaseTransport | None = None
|
|
475
|
+
) -> None:
|
|
476
|
+
self._host = host.rstrip("/")
|
|
477
|
+
self._automations = f"{self._host}/api/v1/entities/workspaces/{workspace_id}/automations"
|
|
478
|
+
self._client = httpx.Client(
|
|
479
|
+
timeout=60.0,
|
|
480
|
+
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/vnd.gooddata.api+json"},
|
|
481
|
+
transport=transport,
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
def close(self) -> None:
|
|
485
|
+
self._client.close()
|
|
486
|
+
|
|
487
|
+
def create(self, entity: dict) -> str:
|
|
488
|
+
alert_id = f"{SETUP_ID_PREFIX}{uuid.uuid4().hex[:12]}"
|
|
489
|
+
body = {"data": {"id": alert_id, "type": "automation", **entity}}
|
|
490
|
+
try:
|
|
491
|
+
self._client.post(self._automations, json=body).raise_for_status()
|
|
492
|
+
except Exception:
|
|
493
|
+
# The server may have stored the alert before the request failed, and the run never gets its id.
|
|
494
|
+
self.delete(alert_id)
|
|
495
|
+
raise
|
|
496
|
+
return alert_id
|
|
497
|
+
|
|
498
|
+
def get(self, alert_id: str) -> dict | None:
|
|
499
|
+
"""The stored alert as ``attributes`` + ``relationships``; None when it does not exist."""
|
|
500
|
+
resp = self._client.get(f"{self._automations}/{alert_id}", params={"include": "ALL"})
|
|
501
|
+
if resp.status_code == 404:
|
|
502
|
+
return None
|
|
503
|
+
resp.raise_for_status()
|
|
504
|
+
data = _envelope(resp).get("data")
|
|
505
|
+
if not isinstance(data, dict):
|
|
506
|
+
raise ValueError(f"Automation {alert_id} response has no data object")
|
|
507
|
+
attributes, relationships = data.get("attributes"), data.get("relationships") or {}
|
|
508
|
+
if not isinstance(attributes, dict) or not isinstance(relationships, dict):
|
|
509
|
+
raise ValueError(f"Automation {alert_id} response has no attributes object or a malformed relationships")
|
|
510
|
+
return {"attributes": attributes, "relationships": relationships}
|
|
511
|
+
|
|
512
|
+
def ids_titled(self, title: str) -> list[str]:
|
|
513
|
+
ids: list[str] = []
|
|
514
|
+
page = 0
|
|
515
|
+
while True:
|
|
516
|
+
resp = self._client.get(self._automations, params={"page": page, "size": _PAGE_SIZE})
|
|
517
|
+
resp.raise_for_status()
|
|
518
|
+
data = _entries(resp, "automations")
|
|
519
|
+
ids += [a["id"] for a in data if (a.get("attributes") or {}).get("title") == title]
|
|
520
|
+
if len(data) < _PAGE_SIZE:
|
|
521
|
+
return ids
|
|
522
|
+
page += 1
|
|
523
|
+
|
|
524
|
+
def delete(self, alert_id: str, *, strict: bool = False) -> None:
|
|
525
|
+
"""Delete an alert; a missing one counts as deleted.
|
|
526
|
+
|
|
527
|
+
Best effort unless ``strict``: a failure is logged, not raised, so a cleanup never hides the run's own
|
|
528
|
+
error. ``strict`` raises instead, for a deletion the run cannot go on without.
|
|
529
|
+
"""
|
|
530
|
+
try:
|
|
531
|
+
resp = self._client.delete(f"{self._automations}/{alert_id}")
|
|
532
|
+
if resp.status_code != 404:
|
|
533
|
+
resp.raise_for_status()
|
|
534
|
+
except Exception as exc:
|
|
535
|
+
if strict:
|
|
536
|
+
raise
|
|
537
|
+
print(f"[CLEANUP] Failed to delete alert {alert_id}: {exc}")
|
|
538
|
+
|
|
539
|
+
def first_channel_id(self) -> str | None:
|
|
540
|
+
"""The organization's notification channel with the lowest id, None when it has none."""
|
|
541
|
+
ids: list[str] = []
|
|
542
|
+
page = 0
|
|
543
|
+
while True:
|
|
544
|
+
resp = self._client.get(
|
|
545
|
+
f"{self._host}/api/v1/entities/notificationChannels", params={"page": page, "size": _PAGE_SIZE}
|
|
546
|
+
)
|
|
547
|
+
resp.raise_for_status()
|
|
548
|
+
data = _entries(resp, "notification channels")
|
|
549
|
+
ids += [c["id"] for c in data]
|
|
550
|
+
if len(data) < _PAGE_SIZE:
|
|
551
|
+
return min(ids) if ids else None
|
|
552
|
+
page += 1
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _envelope(resp: httpx.Response) -> dict:
|
|
556
|
+
body = resp.json()
|
|
557
|
+
if not isinstance(body, dict):
|
|
558
|
+
raise ValueError(f"{resp.request.url} returned {type(body).__name__}, expected a JSON object")
|
|
559
|
+
return body
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _entries(resp: httpx.Response, what: str) -> list[dict]:
|
|
563
|
+
"""The ``data`` list of a listing; every entry an object with a string id."""
|
|
564
|
+
data = _envelope(resp).get("data")
|
|
565
|
+
if not isinstance(data, list) or not all(isinstance(e, dict) and isinstance(e.get("id"), str) for e in data):
|
|
566
|
+
raise ValueError(f"The {what} listing has no data list of objects with an id")
|
|
567
|
+
return data
|
|
@@ -73,27 +73,25 @@ class CatalogMetricAlert:
|
|
|
73
73
|
"""Alert name the user asked for; ``None`` means unasserted."""
|
|
74
74
|
dashboard_id: str | None = None
|
|
75
75
|
"""Dashboard the alert must be bound to; ``None`` means unasserted."""
|
|
76
|
+
expect_alert: bool = True
|
|
77
|
+
"""``False``: the request names nothing the alert can monitor, so no alert may be proposed or created."""
|
|
78
|
+
sensitivity: str | None = None
|
|
79
|
+
"""ANOMALY sensitivity (LOW/MEDIUM/HIGH); ``None`` means unasserted."""
|
|
80
|
+
trigger_interval: str | None = None
|
|
81
|
+
"""Interval of a ONCE_PER_INTERVAL trigger (DAY/WEEK/MONTH/QUARTER/YEAR); ``None`` means unasserted."""
|
|
82
|
+
date_dataset_id: str | None = None
|
|
83
|
+
"""Date dataset an ANOMALY alert detects on; ``None`` means unasserted."""
|
|
84
|
+
setup_turns: tuple[str, ...] = ()
|
|
85
|
+
"""Messages sent in the same conversation before the question, not scored."""
|
|
86
|
+
alternatives: tuple[CatalogMetricAlert, ...] = ()
|
|
87
|
+
"""Complete expectations any one of which passes (``any_of``); empty means this one alone."""
|
|
88
|
+
check_first_proposal: tuple[str, ...] = ()
|
|
89
|
+
"""Fields (``filters``, ``recipients``) also scored on the first proposal, before the simulated user replies."""
|
|
76
90
|
|
|
77
91
|
@classmethod
|
|
78
92
|
def from_dict(cls, d: dict) -> CatalogMetricAlert:
|
|
79
|
-
"""Build a CatalogMetricAlert
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
recipients = list(recipients_raw)
|
|
85
|
-
return cls(
|
|
86
|
-
operator=d.get("operator", "GREATER_THAN"),
|
|
87
|
-
threshold=d.get("threshold"),
|
|
88
|
-
threshold_from=d.get("threshold_from"),
|
|
89
|
-
threshold_to=d.get("threshold_to"),
|
|
90
|
-
trigger=d.get("trigger", "not specified"),
|
|
91
|
-
metric_id=d.get("metric_id"),
|
|
92
|
-
recipients=recipients,
|
|
93
|
-
filters=d.get("filters"),
|
|
94
|
-
attributes=d.get("attributes"),
|
|
95
|
-
granularity=AnomalyDetectionGranularity.parse(d.get("granularity")),
|
|
96
|
-
comparison=d.get("comparison"),
|
|
97
|
-
title=d.get("title"),
|
|
98
|
-
dashboard_id=d.get("dashboard_id"),
|
|
99
|
-
)
|
|
93
|
+
"""Build a CatalogMetricAlert with the parsing and validation a dataset item's expected_output gets."""
|
|
94
|
+
# Imported here: alert_skill imports this module.
|
|
95
|
+
from gooddata_eval.core.agentic.alert_skill import _normalize_expected_output # noqa: PLC0415
|
|
96
|
+
|
|
97
|
+
return _normalize_expected_output(d)
|