From ac05c949cac4dd5dcc8dcf3ee7607c6cf0021cc4 Mon Sep 17 00:00:00 2001 From: huyenthanh09 Date: Wed, 25 Nov 2026 14:56:31 +0700 Subject: [PATCH] feat(gooddata-eval): alert update mode scored on the stored alert - An alert item with `mode: update` states a `setup_alert` (the automation entity) and an `expected_change`. Each run deletes alerts with the same title, creates the setup alert through the API, asks the question, reads the stored alert again and deletes it - update_metric_alert keeps every field it is not given, so its arguments cannot show a field the update lost. The run compares the stored alert before and after instead: alert_update_correct (every expected value stored), alert_update_preserved (no other field changed; timestamps, editors and the generated description ignored), alert_update_called (an update_metric_alert / update_alert_state call on the alert succeeded, also after a failed one) and alert_not_recreated - Changes checked: threshold, operator, trigger, trigger_interval, sensitivity, granularity, title, state, filters, dashboard_id. An unknown key or a change the setup alert cannot take raises before any request - The setup goes to the token owner over the organization's channel unless the item names them, so an item runs in any organization - The simulated user confirms the requested change and declines others - The update scores are in ALERT_CONDITIONAL_SCORES; a failing run reports the update arguments and every field that changed unasked jira: QA-30232 risk: low Co-Authored-By: Claude Opus 5.5 --- packages/gooddata-eval/README.md | 66 ++ .../core/agentic/_alert_update.py | 567 ++++++++++ .../gooddata_eval/core/agentic/alert_skill.py | 295 +++++- .../tests/test_agentic_alert_update.py | 964 ++++++++++++++++++ 4 files changed, 1878 insertions(+), 14 deletions(-) create mode 100644 packages/gooddata-eval/src/gooddata_eval/core/agentic/_alert_update.py create mode 100644 packages/gooddata-eval/tests/test_agentic_alert_update.py diff --git a/packages/gooddata-eval/README.md b/packages/gooddata-eval/README.md index 3212ff3d4..00ef71e95 100644 --- a/packages/gooddata-eval/README.md +++ b/packages/gooddata-eval/README.md @@ -1033,6 +1033,72 @@ a fail. The judge steps are calibrated with `make calibrate-knowledge` (needs `OPENAI_API_KEY`); the CI entry point is `evaluate_agentic_knowledge`. +### `agentic_alert_skill` update items + +An alert item with `"mode": "update"` asks the agent to change an alert that exists before the +question. Each run creates the setup alert through the API, asks `question`, then reads the +stored alert again and deletes it. A setup alert an earlier run left is deleted first; an alert +with the same title that no evaluation created stops the item instead, so give each setup alert +a title unique in the workspace. The simulated user confirms the requested change and declines +any other change. + +```json +{ + "question": "Raise the threshold of my \"Net Sales floor u1\" alert to $60,000.", + "expected_output": { + "mode": "update", + "setup_alert": { + "attributes": { + "title": "Net Sales floor u1", + "state": "ACTIVE", + "alert": { + "execution": { + "measures": [ + { + "localIdentifier": "net_sales", + "definition": {"measure": {"item": {"identifier": {"id": "net_sales", "type": "metric"}}}} + } + ], + "attributes": [], + "filters": [] + }, + "condition": { + "comparison": { + "operator": "LESS_THAN", + "left": {"localIdentifier": "net_sales", "title": "Net Sales"}, + "right": {"value": 50000} + } + }, + "trigger": "ALWAYS" + } + }, + "relationships": {"analyticalDashboard": {"data": {"id": "", "type": "analyticalDashboard"}}} + }, + "expected_change": {"threshold": 60000} + } +} +``` + +- `setup_alert` — the automation entity as the API returns it: `attributes` (with a unique + `title` the agent finds the alert by) and optional `relationships`. Without `recipients` the + alert goes to the token owner; without `notificationChannel` it uses the organization's + channel with the lowest id. +- `expected_change` — the new value of each changed field: `threshold` and `operator` + (comparison and relative alerts), `sensitivity` and `granularity` (anomaly alerts), + `trigger`, `trigger_interval` (with the `ONCE_PER_INTERVAL` trigger), `title`, `state` + (`ACTIVE`/`PAUSED`), `filters` (the whole list, in any order) and `dashboard_id`. A + `trigger` change may set or clear the interval, unless the alert is `ONCE_PER_INTERVAL` + before and after it. + +An update item takes no other key, and a change the setup alert cannot take is rejected before +any request. The run publishes four scores instead of the creation checks: +`alert_update_called` (an `update_metric_alert` or `update_alert_state` call on the alert +succeeded, also after a failed one), `alert_update_correct` (the stored alert holds every +expected value), `alert_update_preserved` (no other stored field changed; the timestamps, +the editors and the generated `description` are not compared) and `alert_not_recreated` +(the alert still exists and the agent created none). A failing run reports the update +arguments and every field that changed unasked. + ### Items asked in a dashboard context (`user_context`) An item can be asked the way a user asks from an open dashboard or an attached widget. diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_alert_update.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_alert_update.py new file mode 100644 index 000000000..0ba5eee5e --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_alert_update.py @@ -0,0 +1,567 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""Update mode of the agentic alert-skill evaluation: the agent changes an alert that exists before the question. + +An item in this mode states the alert to set up and the change its question asks for. Each run creates the +alert through the API, asks the question, and compares the stored alert before and after. The asked fields +must hold the new values, and every other field must be unchanged. ``update_metric_alert`` keeps every field +it is not given, so its arguments cannot show a field the update lost on the way. Only the stored alert can. +""" + +from __future__ import annotations + +import copy +import json +import math +import uuid +from dataclasses import dataclass +from typing import Any, ClassVar + +import httpx + +# Score names, in report order. An update item publishes these and none of the creation checks. +UPDATE_CHECKS = ("alert_update_called", "alert_update_correct", "alert_update_preserved", "alert_not_recreated") +# Tools that change an existing alert: the condition and settings, and the paused/active state. +UPDATE_TOOLS = ("update_metric_alert", "update_alert_state") + +_MODE_UPDATE = "update" +_PAGE_SIZE = 250 +# Keys under which an AFM attribute filter lists the elements it selects (`in`/`notIn`). +_ELEMENT_KEYS = ("values", "uris") +# Every setup alert's id starts with this, so a run deletes only alerts an earlier run left. +SETUP_ID_PREFIX = "eval-update-" +_ITEM_KEYS = ("mode", "setup_alert", "expected_change") + +_ALERT = ("attributes", "alert") +# Server bookkeeping that every write changes, and the text gen-ai generates from the condition when it +# creates the alert. A correct update may rewrite that text, so it is not compared. +_IGNORED_PATHS = ( + ("attributes", "createdAt"), + ("attributes", "modifiedAt"), + ("attributes", "description"), + ("relationships", "createdBy"), + ("relationships", "modifiedBy"), + ("relationships", "automationResults"), +) + +_COMPARISON_OPERATORS = ( + "GREATER_THAN", + "GREATER_THAN_OR_EQUAL_TO", + "LESS_THAN", + "LESS_THAN_OR_EQUAL_TO", + "EQUAL_TO", + "NOT_EQUAL_TO", +) +_RELATIVE_OPERATORS = ("INCREASES_BY", "DECREASES_BY", "CHANGES_BY") +_TRIGGERS = ("ALWAYS", "ONCE", "ONCE_PER_INTERVAL") +_TRIGGER_DISPLAY = {"EVERY TIME": "ALWAYS", "ONE TIME": "ONCE"} +_TRIGGER_INTERVALS = ("DAY", "WEEK", "MONTH", "QUARTER", "YEAR") +_SENSITIVITIES = ("LOW", "MEDIUM", "HIGH") +_GRANULARITIES = ("HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR") +_STATES = ("ACTIVE", "PAUSED") +_CONDITION_KINDS = ("comparison", "relative", "anomaly", "range") +_ENUMS: dict[str, tuple[str, ...]] = { + "trigger": _TRIGGERS, + "trigger_interval": _TRIGGER_INTERVALS, + "sensitivity": _SENSITIVITIES, + "granularity": _GRANULARITIES, + "state": _STATES, +} +# The condition kinds each change applies to; a change missing here applies to every kind. +_KINDS_OF_CHANGE = { + "threshold": ("comparison", "relative"), + "operator": ("comparison", "relative"), + "sensitivity": ("anomaly",), + "granularity": ("anomaly",), +} +_CHANGE_ALIASES = {"dashboard": "dashboard_id", "interval": "trigger_interval", "name": "title"} +_CHANGES = ("threshold", "operator", "trigger", "trigger_interval", "sensitivity", "granularity", "title", "state") +_CHANGES_WITH_SHAPE = ("filters", "dashboard_id") + + +@dataclass(frozen=True) +class AlertUpdateExpectation: + """The alert a run sets up and the change its question asks for.""" + + setup_alert: dict[str, Any] + """The automation entity to create: ``attributes`` and optional ``relationships``, as the API returns them.""" + expected_change: dict[str, Any] + """New value per changed field, by canonical name (``threshold``, ``trigger``, ``filters``, ...).""" + + @property + def title(self) -> str: + return self.setup_alert["attributes"]["title"] + + @property + def condition_kind(self) -> str: + return condition_kind(self.setup_alert) + + +@dataclass +class AlertUpdateEvaluation: + """Scores of one update run.""" + + alert_update_called: bool + """An update tool call on the setup alert succeeded.""" + alert_update_correct: bool + """The stored alert holds every value the item expects to change.""" + alert_update_preserved: bool + """No other field of the stored alert changed.""" + alert_not_recreated: bool + """The setup alert still exists and the agent created no alert.""" + + # The check every other one depends on: without an update call, the others read False. + prerequisite: ClassVar[str] = "alert_update_called" + + def checks(self) -> dict[str, bool]: + return {name: getattr(self, name) for name in UPDATE_CHECKS} + + @property + def strict_pass(self) -> bool: + return all(self.checks().values()) + + +def _canonical(key: object) -> str: + return str(key).strip().lower().replace(" ", "_") + + +def _get(d: dict, *keys: str) -> Any: + """A value by any of ``keys``, case-insensitively; spaces and underscores are interchangeable.""" + by_name = {_canonical(k): v for k, v in d.items()} + for key in keys: + if key in by_name: + return by_name[key] + return None + + +def condition_kind(entity: dict) -> str: + """``comparison``, ``relative``, ``anomaly`` or ``range``: the one key of the alert condition.""" + condition = ((entity.get("attributes") or {}).get("alert") or {}).get("condition") + bodies = {k: v for k, v in condition.items() if v is not None} if isinstance(condition, dict) else {} + if len(bodies) != 1: + raise ValueError(f"setup_alert must have exactly one alert condition, got {list(bodies)}") + [(kind, body)] = bodies.items() + if kind not in _CONDITION_KINDS: + raise ValueError(f"setup_alert condition must be one of {list(_CONDITION_KINDS)}, got {kind!r}") + if not isinstance(body, dict): + raise ValueError(f"setup_alert condition {kind} must be an object, got {body!r}") + return kind + + +def _normalize_setup_alert(value: object) -> dict[str, Any]: + if not isinstance(value, dict): + raise ValueError(f"setup_alert must be an automation entity object, got {value!r}") + unknown = sorted(set(value) - {"attributes", "relationships", "id", "type"}) + if unknown: + raise ValueError(f"setup_alert takes only attributes and relationships, got {unknown}") + attributes = value.get("attributes") + if not isinstance(attributes, dict) or not isinstance(attributes.get("alert"), dict): + raise ValueError("setup_alert.attributes.alert is required") + title = attributes.get("title") + if not isinstance(title, str) or not title.strip(): + # The agent finds the alert by its title, and each run deletes alerts with the same title first. + raise ValueError("setup_alert.attributes.title is required: it identifies the alert to the agent") + relationships = value.get("relationships") + relationships = {} if relationships is None else relationships + if not isinstance(relationships, dict): + raise ValueError(f"setup_alert.relationships must be an object, got {relationships!r}") + entity = {"attributes": copy.deepcopy(attributes), "relationships": copy.deepcopy(relationships)} + for section, key in _IGNORED_PATHS: + if key != "description": + entity[section].pop(key, None) + condition_kind(entity) + return entity + + +def _finite(value: float) -> bool: + """Whether the scorer can compare ``value`` as a float: not NaN, not infinite, not too large.""" + try: + return math.isfinite(float(value)) + except OverflowError: + return False + + +def _normalize_change(key: str, value: object, kind: str) -> object: + kinds = _KINDS_OF_CHANGE.get(key) + if kinds is not None and kind not in kinds: + raise ValueError( + f"expected_change.{key} applies only to {' and '.join(kinds)} alerts, the setup alert is {kind}" + ) + if key == "threshold": + if isinstance(value, bool) or not isinstance(value, int | float) or not _finite(value): + raise ValueError(f"expected_change.threshold must be a finite number, got {value!r}") + return value + if key == "operator": + operators = _COMPARISON_OPERATORS if kind == "comparison" else _RELATIVE_OPERATORS + canonical = str(value).strip().upper() + if canonical not in operators: + raise ValueError(f"expected_change.operator must be one of {list(operators)}, got {value!r}") + return canonical + if key in _ENUMS: + canonical = str(value).strip().upper() + canonical = _TRIGGER_DISPLAY.get(canonical, canonical) if key == "trigger" else canonical + if canonical not in _ENUMS[key]: + raise ValueError(f"expected_change.{key} must be one of {list(_ENUMS[key])}, got {value!r}") + return canonical + if key == "filters": + # An empty object would fit any stored filter; `[]` (no filter at all) stays valid. + if not isinstance(value, list) or not all(isinstance(f, dict) and f for f in value): + raise ValueError(f"expected_change.filters must be a list of non-empty filter objects, got {value!r}") + return value + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"expected_change.{key} must be a non-empty string, got {value!r}") + return value + + +def update_expectation(expected: dict) -> AlertUpdateExpectation | None: + """The update expectation of an item in update mode; None only when ``expected`` has no ``mode`` key. + + Raises on a malformed item, so a typo never reads green: a ``mode`` other than ``update`` (null + included), an unknown key, a change the setup alert cannot take, or a trigger interval without the + ONCE_PER_INTERVAL trigger. + """ + # Only an item without the key is a creation item: `mode: null` next to update keys is a typo. + if "mode" not in {_canonical(k) for k in expected}: + return None + mode = _get(expected, "mode") + if not isinstance(mode, str) or mode.strip().lower() != _MODE_UPDATE: + raise ValueError(f"mode must be {_MODE_UPDATE!r}, got {mode!r}") + unknown = sorted(k for k in expected if _canonical(k) not in _ITEM_KEYS) + if unknown: + # A creation key next to update mode would be ignored, and the item would read green without it. + raise ValueError(f"an update item takes only {list(_ITEM_KEYS)}, got also {unknown}") + setup = _normalize_setup_alert(_get(expected, "setup_alert")) + kind = condition_kind(setup) + raw_change = _get(expected, "expected_change") + if not isinstance(raw_change, dict) or not raw_change: + raise ValueError(f"expected_change must name at least one field, got {raw_change!r}") + change: dict[str, Any] = {} + for raw_key, value in raw_change.items(): + key = _CHANGE_ALIASES.get(_canonical(raw_key), _canonical(raw_key)) + if key not in _CHANGES + _CHANGES_WITH_SHAPE: + raise ValueError( + f"expected_change.{raw_key} is not a field update mode checks; use one of " + f"{list(_CHANGES + _CHANGES_WITH_SHAPE)}" + ) + if key in change: + raise ValueError(f"expected_change names {key} twice, the second time as {raw_key!r}") + change[key] = _normalize_change(key, value, kind) + if "trigger_interval" in change: + trigger = change.get("trigger", (setup["attributes"]["alert"].get("trigger") or "").upper()) + if trigger != "ONCE_PER_INTERVAL": + raise ValueError(f"expected_change.trigger_interval needs the ONCE_PER_INTERVAL trigger, got {trigger!r}") + return AlertUpdateExpectation(setup_alert=setup, expected_change=change) + + +def setup_entity(expectation: AlertUpdateExpectation, *, current_user_id: str, channel_id: str | None) -> dict: + """The entity a run creates: the item's setup alert, sent to the current user over the org's channel. + + An item states neither, so that it runs in any organization: the token owner differs per environment, + and so do the notification channel ids. + """ + entity = copy.deepcopy(expectation.setup_alert) + relationships = entity["relationships"] + relationships.setdefault("recipients", {"data": [{"id": current_user_id, "type": "user"}]}) + if "notificationChannel" not in relationships and channel_id is not None: + relationships["notificationChannel"] = {"data": {"id": channel_id, "type": "notificationChannel"}} + return entity + + +def needs_channel(expectation: AlertUpdateExpectation) -> bool: + return "notificationChannel" not in expectation.setup_alert["relationships"] + + +def _owned_paths(key: str, kind: str, *, keeps_interval: bool = False) -> tuple[tuple[str, ...], ...]: + """The stored paths a change of ``key`` may rewrite; a difference under any other path is a lost field. + + ``keeps_interval``: the trigger stays ONCE_PER_INTERVAL, so a trigger change must leave the interval as it is. + """ + condition = (*_ALERT, "condition", kind) + owned: dict[str, tuple[tuple[str, ...], ...]] = { + "threshold": ((*condition, "right", "value"),) if kind == "comparison" else ((*condition, "threshold"),), + "operator": ((*condition, "operator"),), + # Leaving ONCE_PER_INTERVAL clears the interval, and entering it sets one. + "trigger": ((*_ALERT, "trigger"),) if keeps_interval else ((*_ALERT, "trigger"), (*_ALERT, "interval")), + "trigger_interval": ((*_ALERT, "interval"),), + "sensitivity": ((*condition, "sensitivity"),), + "granularity": ((*condition, "granularity"),), + "title": (("attributes", "title"),), + "state": (("attributes", "state"),), + # The filter list, the dashboard dialog's record of which filters it shows and hides, and the labels + # they use. The rest of the metadata, such as the widget the alert was set on, is not the change's. + "filters": ( + (*_ALERT, "execution", "filters"), + ("attributes", "metadata", "filters"), + ("attributes", "metadata", "visibleFilters"), + ("relationships", "labels"), + ), + "dashboard_id": (("relationships", "analyticalDashboard"),), + } + return owned[key] + + +def _at(entity: dict, path: tuple[str, ...]) -> Any: + node: Any = entity + for key in path: + if not isinstance(node, dict): + return None + node = node.get(key) + return node + + +def _stored_value(entity: dict, key: str, kind: str) -> Any: + if key == "dashboard_id": + return _at(entity, ("relationships", "analyticalDashboard", "data", "id")) + if key == "threshold" and kind == "relative": + return _at(entity, (*_ALERT, "condition", kind, "threshold", "value")) + return _at(entity, _owned_paths(key, kind)[0]) + + +def _contains(expected: object, actual: object) -> bool: + """Whether ``expected`` is a recursive subset of ``actual``: a filter may carry ids the item omits.""" + if isinstance(expected, dict) and isinstance(actual, dict): + return all(k in actual and _contains_value(k, v, actual[k]) for k, v in expected.items()) + if isinstance(expected, list) and isinstance(actual, list): + return len(expected) == len(actual) and all(_contains(e, a) for e, a in zip(expected, actual)) + return expected == actual + + +def _same_filters(expected: list, actual: object) -> bool: + """The same filters in any order; each stored filter may add a localIdentifier and defaults. + + One expected filter can fit several stored ones, so every pairing is tried, not the first fit. + """ + if not isinstance(actual, list) or len(actual) != len(expected): + return False + fits = [[i for i, got in enumerate(actual) if _contains(want, got)] for want in expected] + owner: dict[int, int] = {} + return all(_assign(fits, want, owner, set()) for want in range(len(fits))) + + +def _assign(fits: list[list[int]], want: int, owner: dict[int, int], visited: set[int]) -> bool: + """Give expected filter ``want`` a stored filter, moving earlier owners along an augmenting path.""" + for got in fits[want]: + if got in visited: + continue + visited.add(got) + if got not in owner or _assign(fits, owner[got], owner, visited): + owner[got] = want + return True + return False + + +def _change_applied(key: str, expected: Any, stored: Any) -> bool: + if key == "threshold": + return ( + isinstance(stored, int | float) + and not isinstance(stored, bool) + and math.isclose(float(stored), float(expected), rel_tol=1e-9, abs_tol=1e-12) + ) + if key == "filters": + return _same_filters(expected, stored) + return stored == expected + + +def _ignored(path: tuple[str, ...], owned: list[tuple[str, ...]]) -> bool: + return any(path[: len(prefix)] == prefix for prefix in [*_IGNORED_PATHS, *owned]) + + +def _contains_value(key: str, expected: object, actual: object) -> bool: + # The elements an attribute filter selects are a set: the agent may list them in another order. + if key in _ELEMENT_KEYS and isinstance(expected, list) and isinstance(actual, list): + return sorted(map(json.dumps, expected)) == sorted(map(json.dumps, actual)) + return _contains(expected, actual) + + +def _differences(before: object, after: object, path: tuple[str, ...], out: list[dict]) -> None: + # An object that appears or disappears is compared field by field, so an owned child such as + # metadata.visibleFilters can be added to an alert that had no metadata. + if isinstance(before, dict) and after is None: + after = {} + elif before is None and isinstance(after, dict): + before = {} + if isinstance(before, dict) and isinstance(after, dict): + for key in sorted(set(before) | set(after)): + _differences(before.get(key), after.get(key), (*path, key), out) + elif before != after: + # A missing key and a null read the same: the API omits some nulls on one write and not another. + out.append({"path": ".".join(path), "before": before, "after": after}) + + +def unexpected_changes(expectation: AlertUpdateExpectation, before: dict, after: dict) -> list[dict]: + """Every stored field that changed although the item did not ask for it, as ``{path, before, after}``.""" + kind = condition_kind(before) + change = expectation.expected_change + keeps_interval = change.get("trigger") == _at(before, (*_ALERT, "trigger")) == "ONCE_PER_INTERVAL" + owned = [path for key in change for path in _owned_paths(key, kind, keeps_interval=keeps_interval)] + diffs: list[dict] = [] + _differences(before, after, (), diffs) + return [d for d in diffs if not _ignored(tuple(d["path"].split(".")), owned)] + + +def evaluate_update( + expectation: AlertUpdateExpectation, + *, + before: dict, + after: dict | None, + update_called: bool, + alert_created: bool, +) -> tuple[AlertUpdateEvaluation, list[dict]]: + """Score one run from the stored alert before the question and after it; also returns the unexpected changes. + + ``after`` is None when the alert no longer exists: the agent deleted it, or deleted and recreated it. + """ + if after is None: + evaluation = AlertUpdateEvaluation( + alert_update_called=update_called, + alert_update_correct=False, + alert_update_preserved=False, + alert_not_recreated=False, + ) + return evaluation, [] + kind = condition_kind(before) + applied = all( + _change_applied(key, value, _stored_value(after, key, kind)) + for key, value in expectation.expected_change.items() + ) + changes = unexpected_changes(expectation, before, after) + evaluation = AlertUpdateEvaluation( + alert_update_called=update_called, + alert_update_correct=update_called and applied, + alert_update_preserved=update_called and not changes, + alert_not_recreated=not alert_created, + ) + return evaluation, changes + + +def targets_alert(args: dict, alert_id: str) -> bool: + """Whether an update call names ``alert_id``: ``automation_id``, or ``automation_ids``. + + ``automation_ids`` is a list, one id, or a list encoded as a JSON string, which the tool also accepts. + """ + if args.get("automation_id") == alert_id: + return True + ids = args.get("automation_ids") + if isinstance(ids, str) and ids.strip().startswith("["): + try: + ids = json.loads(ids) + except json.JSONDecodeError: + return False + return ids == alert_id or (isinstance(ids, list) and alert_id in ids) + + +def update_sim_user_prompt(question: str, title: str) -> str: + """The simulated user of an update item: it confirms the requested change and nothing else.""" + return ( + "You are a user who asked an AI agent to change one of your existing alerts.\n" + f'Your request was: "{question}"\n' + f'The alert is the one titled "{title}".\n' + "Rules you MUST follow:\n" + "1. Your goal is exactly the change in your request. Never ask for any other change.\n" + "2. If the agent asks you to confirm that change, or shows a summary or proposal of it, confirm: " + "'Yes, please apply that change.'\n" + f'3. If the agent asks which alert you mean, it is the one titled "{title}".\n' + "4. If the agent proposes to change anything else, to create a new alert or to delete this one, " + "decline and repeat your request.\n" + "5. If the agent asks about a setting your request does not mention, tell it to keep the current value.\n" + "Reply concisely and directly." + ) + + +class AutomationApi: + """The workspace automation entities one update run creates, reads and deletes.""" + + def __init__( + self, host: str, token: str, workspace_id: str, *, transport: httpx.BaseTransport | None = None + ) -> None: + self._host = host.rstrip("/") + self._automations = f"{self._host}/api/v1/entities/workspaces/{workspace_id}/automations" + self._client = httpx.Client( + timeout=60.0, + headers={"Authorization": f"Bearer {token}", "Content-Type": "application/vnd.gooddata.api+json"}, + transport=transport, + ) + + def close(self) -> None: + self._client.close() + + def create(self, entity: dict) -> str: + alert_id = f"{SETUP_ID_PREFIX}{uuid.uuid4().hex[:12]}" + body = {"data": {"id": alert_id, "type": "automation", **entity}} + try: + self._client.post(self._automations, json=body).raise_for_status() + except Exception: + # The server may have stored the alert before the request failed, and the run never gets its id. + self.delete(alert_id) + raise + return alert_id + + def get(self, alert_id: str) -> dict | None: + """The stored alert as ``attributes`` + ``relationships``; None when it does not exist.""" + resp = self._client.get(f"{self._automations}/{alert_id}", params={"include": "ALL"}) + if resp.status_code == 404: + return None + resp.raise_for_status() + data = _envelope(resp).get("data") + if not isinstance(data, dict): + raise ValueError(f"Automation {alert_id} response has no data object") + attributes, relationships = data.get("attributes"), data.get("relationships") or {} + if not isinstance(attributes, dict) or not isinstance(relationships, dict): + raise ValueError(f"Automation {alert_id} response has no attributes object or a malformed relationships") + return {"attributes": attributes, "relationships": relationships} + + def ids_titled(self, title: str) -> list[str]: + ids: list[str] = [] + page = 0 + while True: + resp = self._client.get(self._automations, params={"page": page, "size": _PAGE_SIZE}) + resp.raise_for_status() + data = _entries(resp, "automations") + ids += [a["id"] for a in data if (a.get("attributes") or {}).get("title") == title] + if len(data) < _PAGE_SIZE: + return ids + page += 1 + + def delete(self, alert_id: str, *, strict: bool = False) -> None: + """Delete an alert; a missing one counts as deleted. + + Best effort unless ``strict``: a failure is logged, not raised, so a cleanup never hides the run's own + error. ``strict`` raises instead, for a deletion the run cannot go on without. + """ + try: + resp = self._client.delete(f"{self._automations}/{alert_id}") + if resp.status_code != 404: + resp.raise_for_status() + except Exception as exc: + if strict: + raise + print(f"[CLEANUP] Failed to delete alert {alert_id}: {exc}") + + def first_channel_id(self) -> str | None: + """The organization's notification channel with the lowest id, None when it has none.""" + ids: list[str] = [] + page = 0 + while True: + resp = self._client.get( + f"{self._host}/api/v1/entities/notificationChannels", params={"page": page, "size": _PAGE_SIZE} + ) + resp.raise_for_status() + data = _entries(resp, "notification channels") + ids += [c["id"] for c in data] + if len(data) < _PAGE_SIZE: + return min(ids) if ids else None + page += 1 + + +def _envelope(resp: httpx.Response) -> dict: + body = resp.json() + if not isinstance(body, dict): + raise ValueError(f"{resp.request.url} returned {type(body).__name__}, expected a JSON object") + return body + + +def _entries(resp: httpx.Response, what: str) -> list[dict]: + """The ``data`` list of a listing; every entry an object with a string id.""" + data = _envelope(resp).get("data") + if not isinstance(data, list) or not all(isinstance(e, dict) and isinstance(e.get("id"), str) for e in data): + raise ValueError(f"The {what} listing has no data list of objects with an id") + return data diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/alert_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/alert_skill.py index a31aa5685..b77e29bd6 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/alert_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/alert_skill.py @@ -15,6 +15,20 @@ import httpx from gooddata_sdk import GoodDataSdk +from gooddata_eval.core.agentic._alert_update import ( + SETUP_ID_PREFIX, + UPDATE_CHECKS, + UPDATE_TOOLS, + AlertUpdateEvaluation, + AlertUpdateExpectation, + AutomationApi, + evaluate_update, + needs_channel, + setup_entity, + targets_alert, + update_expectation, + update_sim_user_prompt, +) from gooddata_eval.core.agentic._catalog import AnomalyDetectionGranularity, CatalogMetricAlert from gooddata_eval.core.agentic._failed_runs import build_failed_runs from gooddata_eval.core.agentic._failure_message import failed_checks_from @@ -121,7 +135,7 @@ # The only check of an item that expects no alert; it replaces every other check. _NO_ALERT_CHECK = "alert_not_proposed" # Score names published only by an item that states the matching expectation (gdc-nas combo_report). -ALERT_CONDITIONAL_SCORES = (*_CONDITIONAL_ALERT_CHECKS, _NO_ALERT_CHECK) +ALERT_CONDITIONAL_SCORES = (*_CONDITIONAL_ALERT_CHECKS, _NO_ALERT_CHECK, *UPDATE_CHECKS) _SENSITIVITIES = ("LOW", "MEDIUM", "HIGH") # What create_metric_alert applies to an ANOMALY alert when `sensitivity` is left out, per its own contract. @@ -556,6 +570,21 @@ def _named_automation_ids(tool_call_events: list[ToolCallEvent]) -> set[str]: return {i for i in ids if isinstance(i, str) and i} +def _unrecorded_alert_ids( + host: str, token: str, workspace_id: str, events: list[ToolCallEvent], recorded: set[str], existing: set[str] | None +) -> list[str]: + """Alerts the agent named and the run created, although no create result recorded them. + + ``existing`` is the workspace's automations before the run; without a complete listing before and + after it, an alert that existed before could look new, so nothing is returned. + """ + unseen = _named_automation_ids(events) - recorded + if not unseen or existing is None: + return [] + now = _automation_ids(host, token, workspace_id) or set() + return sorted((unseen & now) - existing) + + def _resolve_current_user_id(host: str, token: str) -> str | None: """Id of the user that owns ``token``, or None if the profile cannot be read. @@ -903,6 +932,22 @@ def _no_alert_sim_user_prompt(question: str) -> str: ) +def generate_simulated_update_response( + agent_message: str, expectation: AlertUpdateExpectation, conversation_history: list, question: str +) -> str: + """Simulated-user reply in an update conversation (gpt-4o): it confirms the requested change only.""" + if _OpenAI is None: + raise RuntimeError( + "openai package is required for generate_simulated_update_response. " + "Install the [llm-judge] extra: pip install 'gooddata-eval[llm-judge]'" + ) + api_key = os.environ.get("OPENAI_API_KEY") + if not api_key: + raise OSError("OPENAI_API_KEY environment variable is not set") + prompt = update_sim_user_prompt(question, expectation.title) + return _ask_simulated_user(_OpenAI(api_key=api_key), prompt, conversation_history, agent_message) + + def _delete_alert(sdk: GoodDataSdk, workspace_id: str, alert_id: str) -> None: """Best-effort delete of an alert (automation) created during evaluation. @@ -968,7 +1013,7 @@ class AlertRunResult: conversation_id: str alert_id: str | None - eval: AlertEvaluation + eval: AlertEvaluation | AlertUpdateEvaluation actual_alert_arguments: dict total_turns: int = 0 total_steps: int = 0 @@ -1583,6 +1628,21 @@ def run_agentic_alert_skill( if max_iterations < 1: # With no turn the agent never gets the question, and a no-alert item would pass unasked. raise ValueError(f"max_iterations must be at least 1, got {max_iterations}") + update = update_expectation(expected_output) + if update is not None: + return _run_agentic_alert_update( + host=host, + token=token, + workspace_id=workspace_id, + question=question, + expectation=update, + k=k, + max_iterations=max_iterations, + initial_conversation_id=initial_conversation_id, + reasoning_effort=reasoning_effort, + agent_id=agent_id, + user_context=user_context, + ) expected = _normalize_expected_output(expected_output) current_user_id: str | None = None # A no-alert item scores no recipients, so it needs no current user. `any_of` options share theirs. @@ -1812,12 +1872,12 @@ def _track_writes(events: list[ToolCallEvent]) -> _AlertCalls: finally: for created_id in dict.fromkeys(alert_ids_to_delete): _delete_alert(sdk, workspace_id, created_id) - unseen = _named_automation_ids(all_tool_call_events + partial_events) - set(alert_ids_to_delete) - if unseen and existing_ids is not None: - now = _automation_ids(host, token, workspace_id) or set() - for leaked_id in sorted((unseen & now) - existing_ids): - print(f"[CLEANUP] Deleting alert {leaked_id}: created, but its create call was not in the turn") - _delete_alert(sdk, workspace_id, leaked_id) + events = all_tool_call_events + partial_events + for leaked_id in _unrecorded_alert_ids( + host, token, workspace_id, events, set(alert_ids_to_delete), existing_ids + ): + print(f"[CLEANUP] Deleting alert {leaked_id}: created, but its create call was not in the turn") + _delete_alert(sdk, workspace_id, leaked_id) # After the alerts: an alert on a created metric would keep that metric in use. for metric_id in dict.fromkeys(metric_ids_to_delete): _delete_metric(sdk, workspace_id, metric_id) @@ -1838,9 +1898,10 @@ def _track_writes(events: list[ToolCallEvent]) -> _AlertCalls: client.delete_conversation(conv_id) finally: client.close() + return _summarize(run_results) + - pass_at_k = any(r.eval.strict_pass for r in run_results) - pass_power_k = all(r.eval.strict_pass for r in run_results) +def _summarize(run_results: list[AlertRunResult]) -> AgenticAlertSummary: # A passing run first: with `any_of`, a failing run scored against a larger option can have # more true checks than a passing one. best = max( @@ -1849,12 +1910,216 @@ def _track_writes(events: list[ToolCallEvent]) -> _AlertCalls: ) return AgenticAlertSummary( run_results=run_results, - pass_at_k=pass_at_k, - pass_power_k=pass_power_k, + pass_at_k=any(r.eval.strict_pass for r in run_results), + pass_power_k=all(r.eval.strict_pass for r in run_results), best=best, ) +def _update_calls(tool_call_events: list[ToolCallEvent], alert_id: str) -> tuple[list[dict], bool]: + """The arguments of every update call of a turn, and whether one of them changed ``alert_id``. + + The agent may retry after an error, for example after passing ``automation_ids`` as a string where + the tool wants a list, so any call that returned a result without an error counts. + """ + args_seen: list[dict] = [] + updated = False + for tc in tool_call_events: + if tc.function_name not in UPDATE_TOOLS: + continue + args = tc.parsed_arguments() + if not isinstance(args, dict): + # Arguments that decode to a list or a scalar name no alert: the call is a failed attempt. + args_seen.append({"tool": tc.function_name, "arguments": args}) + continue + args_seen.append({"tool": tc.function_name, **args}) + result = tc.parsed_result() + # A call cut off by a broken stream has no result, so it is not known to have changed anything. + succeeded = isinstance(result, dict) and not _alert_call_failed(result) + updated = updated or (targets_alert(args, alert_id) and succeeded) + return args_seen, updated + + +def _run_agentic_alert_update( + host: str, + token: str, + workspace_id: str, + question: str, + expectation: AlertUpdateExpectation, + k: int, + max_iterations: int, + initial_conversation_id: str | None, + reasoning_effort: ReasoningEffort | None, + agent_id: str | None, + user_context: dict | None, +) -> AgenticAlertSummary: + """Run an update item K times: per run, create the setup alert, ask, and compare the stored alert.""" + current_user_id = _resolve_current_user_id(host, token) + if current_user_id is None: + raise RuntimeError("Cannot set up the alert to update: the token owner's user id could not be resolved") + api = AutomationApi(host, token, workspace_id) + client = ChatClient( + host=host, + token=token, + workspace_id=workspace_id, + reasoning_effort=reasoning_effort, + agent_id=agent_id, + user_context=user_context, + ) + sdk = GoodDataSdk.create(host, token) + run_results: list[AlertRunResult] = [] + + def _run_once(conv_id: str, setup: dict) -> AlertRunResult: + # An alert with the same title would make the agent ask which one is meant. One a crashed run left + # is removed, and must be gone before the next is created; any other alert is not the run's to delete. + same_title = api.ids_titled(expectation.title) + foreign = [i for i in same_title if not i.startswith(SETUP_ID_PREFIX)] + if foreign: + raise RuntimeError( + f"Workspace {workspace_id} already has alerts titled {expectation.title!r} that no evaluation " + f"created: {foreign}. Rename them or give the item's setup alert a unique title." + ) + for stale_id in same_title: + api.delete(stale_id, strict=True) + # Taken before the run, so cleanup by a named id never touches an alert the run did not create. + existing_ids = _automation_ids(host, token, workspace_id) + # Events of a turn that broke mid-stream: not part of the run's record, but they can name an alert. + partial_events: list[ToolCallEvent] = [] + all_tool_call_events: list[ToolCallEvent] = [] + alert_id = api.create(setup) + alert_ids_to_delete: list[str] = [alert_id] + metric_ids_to_delete: list[str] = [] + run_started = time.monotonic() + try: + before = api.get(alert_id) + if before is None: + raise RuntimeError(f"The setup alert {alert_id} cannot be read back after it was created") + update_args: list[dict] = [] + update_called = False + alert_created = False + reasoning_steps: list[str] = [] + response_id: str | None = None + all_reasoning_step_events: list[ReasoningStepEvent] = [] + turn_offset, tool_index_offset, reasoning_index_offset = 0.0, 0, 0 + conversation_history: list = [] + current_question = question + turns = steps = turns_used = 0 + exit_reason = LoopExit.BUDGET_EXHAUSTED + + def _track_writes(events: list[ToolCallEvent]) -> None: + nonlocal update_called, alert_created + created = _extract_alert_calls(events) + alert_created = alert_created or created.created + alert_ids_to_delete.extend(created.created_ids) + metric_ids_to_delete.extend(_extract_created_metric_ids(events)) + args, updated = _update_calls(events, alert_id) + update_args.extend(args) + update_called = update_called or updated + + for iteration in range(max_iterations): + turns_used = iteration + 1 + try: + chat_result = client.send_message(conv_id, current_question) + except ChatError as exc: + print(f"[CHAT] send_message failed for conversation {conv_id}: {exc}") + # The stream can break after a tool call already changed or created an alert. + partial = exc.partial_result + if partial is not None: + reasoning_steps.extend(partial.reasoning_steps or []) + response_id = partial.response_id or response_id + partial_events.extend(partial.tool_call_events or []) + _track_writes(partial.tool_call_events or []) + exit_reason = chat_failure_exit(exc) + break + turns += 1 + steps += chat_result.reasoning_step_count + reasoning_steps.extend(chat_result.reasoning_steps or []) + response_id = chat_result.response_id or response_id + turn_offset, tool_index_offset, reasoning_index_offset = shift_and_index_events( + chat_result, + turn_offset=turn_offset, + tool_index_offset=tool_index_offset, + reasoning_index_offset=reasoning_index_offset, + ) + all_tool_call_events.extend(chat_result.tool_call_events or []) + all_reasoning_step_events.extend(chat_result.reasoning_step_events or []) + _track_writes(chat_result.tool_call_events or []) + if update_called: + exit_reason = LoopExit.SUCCESS + break + response_text = render_turn_for_simulated_user(chat_result) + if not response_text: + exit_reason = LoopExit.AGENT_SILENT + break + if iteration >= max_iterations - 1: + break + try: + follow_up = generate_simulated_update_response( + response_text, expectation, conversation_history, question + ) + except Exception as exc: # noqa: BLE001 -- harness-side fault; end only this run + print(f"[SIM-USER] Simulated reply failed for conversation {conv_id}: {exc}") + exit_reason = LoopExit.SIMULATED_USER_FAILED + break + conversation_history.append({"role": "assistant", "content": response_text}) + conversation_history.append({"role": "user", "content": follow_up}) + current_question = follow_up + + ev, changes = evaluate_update( + expectation, + before=before, + after=api.get(alert_id), + update_called=update_called, + alert_created=alert_created, + ) + return AlertRunResult( + conversation_id=conv_id, + alert_id=alert_id, + eval=ev, + # The update arguments and the fields that changed unasked: what a failing run is triaged on. + actual_alert_arguments={"update_calls": update_args, "unexpected_changes": changes}, + total_turns=turns, + total_steps=steps, + reasoning_steps=reasoning_steps, + response_id=response_id, + tool_call_events=all_tool_call_events, + reasoning_step_events=all_reasoning_step_events, + exit_reason=exit_reason, + turns_used=turns_used, + run_latency_s=time.monotonic() - run_started, + ) + finally: + for created_id in dict.fromkeys(alert_ids_to_delete): + api.delete(created_id) + events = all_tool_call_events + partial_events + for leaked_id in _unrecorded_alert_ids( + host, token, workspace_id, events, set(alert_ids_to_delete), existing_ids + ): + print(f"[CLEANUP] Deleting alert {leaked_id}: created, but its create call was not in the turn") + api.delete(leaked_id) + for metric_id in dict.fromkeys(metric_ids_to_delete): + _delete_metric(sdk, workspace_id, metric_id) + + try: + channel_id = api.first_channel_id() if needs_channel(expectation) else None + setup = setup_entity(expectation, current_user_id=current_user_id, channel_id=channel_id) + for run in range(k): + # The first run may continue the caller's conversation, which the caller keeps. + if run == 0 and initial_conversation_id is not None: + conv_id, owned = initial_conversation_id, False + else: + conv_id, owned = client.create_conversation(), True + try: + run_results.append(_run_once(conv_id, setup)) + finally: + if owned: + client.delete_conversation(conv_id) + finally: + client.close() + api.close() + return _summarize(run_results) + + class AlertSkillAssertionError(AgenticAssertionError): """Raised when an alert-skill evaluation fails.""" @@ -1880,9 +2145,11 @@ def _run_detail(run: AlertRunResult) -> dict: def _failed_checks(run: AlertRunResult) -> list[dict]: """The checks this run failed, by name. The arguments the run sent are in its detail. - Every other check reads False when no alert was created, so then only that one is named. + Every other check reads False when no alert was created, or for an update item when no update + call succeeded, so then only that one is named. """ - return failed_checks_from(run.eval.checks(), prerequisite="alert_created") + prerequisite = run.eval.prerequisite if isinstance(run.eval, AlertUpdateEvaluation) else "alert_created" + return failed_checks_from(run.eval.checks(), prerequisite=prerequisite) def evaluate_agentic_alert_skill( diff --git a/packages/gooddata-eval/tests/test_agentic_alert_update.py b/packages/gooddata-eval/tests/test_agentic_alert_update.py new file mode 100644 index 000000000..45b4291ad --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_alert_update.py @@ -0,0 +1,964 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +# SPDX-License-Identifier: LicenseRef-GoodData-Enterprise +import copy +import json +from collections.abc import Callable +from types import EllipsisType +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from gooddata_eval.core.agentic._alert_update import ( + AlertUpdateEvaluation, + AutomationApi, + evaluate_update, + setup_entity, + targets_alert, + update_expectation, + update_sim_user_prompt, +) +from gooddata_eval.core.agentic.alert_skill import ( + ALERT_CONDITIONAL_SCORES, + AlertRunResult, + _failed_checks, + _update_calls, + generate_simulated_update_response, + run_agentic_alert_skill, +) +from gooddata_eval.core.chat.sse_client import ChatError +from gooddata_eval.core.models import ChatResult, LoopExit, ToolCallEvent + +# Changes the stored alert in place, the way the agent's update did. +Edit = Callable[[dict], None] + +_CATEGORY_FILTER = { + "positiveAttributeFilter": { + "label": {"identifier": {"id": "product_category", "type": "label"}}, + "in": {"values": ["Clothing"]}, + } +} +_LAST_MONTH = { + "relativeDateFilter": { + "dataset": {"identifier": {"id": "date", "type": "dataset"}}, + "granularity": "MONTH", + "from": -1, + "to": -1, + } +} +_NET_SALES = { + "localIdentifier": "net_sales", + "definition": {"measure": {"item": {"identifier": {"id": "net_sales", "type": "metric"}}}}, +} + +# Trimmed from a stored alert the agent created on the eval fixture (probe 2026-11-25). +_COMPARISON_SETUP = { + "attributes": { + "title": "Net Sales floor u1", + "state": "ACTIVE", + "externalRecipients": [{"email": "ops@example.com"}], + "metadata": {"visibleFilters": [{"localIdentifier": "genai_vf1", "title": "Product category"}]}, + "alert": { + "execution": { + "measures": [_NET_SALES], + "filters": [ + { + "positiveAttributeFilter": { + **_CATEGORY_FILTER["positiveAttributeFilter"], + "localIdentifier": "genai_vf1", + } + }, + {"relativeDateFilter": {**_LAST_MONTH["relativeDateFilter"], "localIdentifier": "genai_vf2"}}, + ], + "attributes": [], + }, + "condition": { + "comparison": { + "operator": "LESS_THAN", + "left": {"localIdentifier": "net_sales", "format": "$#,##0", "title": "Net Sales"}, + "right": {"value": 50000.0}, + } + }, + "trigger": "ALWAYS", + }, + }, + "relationships": {"analyticalDashboard": {"data": {"id": "dash-overview", "type": "analyticalDashboard"}}}, +} +_ANOMALY_SETUP = { + "attributes": { + "title": "Sales anomaly u4", + "state": "ACTIVE", + "alert": { + "execution": {"measures": [_NET_SALES], "filters": [], "attributes": []}, + "condition": { + "anomaly": { + "measure": {"localIdentifier": "net_sales", "format": "$#,##0", "title": "Net Sales"}, + "sensitivity": "MEDIUM", + "granularity": "DAY", + "dataset": {"identifier": {"id": "date", "type": "dataset"}}, + } + }, + "trigger": "ALWAYS", + }, + }, +} +_RELATIVE_SETUP = { + "attributes": { + "title": "Sales MoM r1", + "alert": { + "execution": {"measures": [_NET_SALES], "filters": [_LAST_MONTH], "attributes": []}, + "condition": { + "relative": { + "operator": "INCREASES_BY", + "measure": {"operator": "CHANGE", "left": {"localIdentifier": "net_sales", "title": "Net Sales"}}, + "threshold": {"value": 0.1}, + } + }, + "trigger": "ALWAYS", + }, + }, +} + + +def _item(setup: dict, **change: object) -> dict: + return {"Mode": "update", "Setup alert": setup, "Expected change": change} + + +def _stored(setup: dict, edit: Edit | None = None) -> dict: + """The alert as the API returns it after the run created it, optionally changed by ``edit``.""" + entity = copy.deepcopy(setup) + entity.setdefault("relationships", {}) + entity["attributes"]["createdAt"] = "2026-11-25 07:00" + entity["attributes"]["description"] = "Alert when net_sales LESS_THAN 50000.0" + entity["relationships"]["recipients"] = {"data": [{"id": "user-1", "type": "user"}]} + entity["relationships"]["notificationChannel"] = {"data": {"id": "defaultSmtp", "type": "notificationChannel"}} + if edit is not None: + edit(entity) + entity["attributes"]["modifiedAt"] = "2026-11-25 07:01" + return entity + + +def _evaluate( + item: dict, edit: Edit | EllipsisType | None, *, update_called: bool = True, alert_created: bool = False +) -> tuple[AlertUpdateEvaluation, list[dict]]: + """Score ``edit`` applied to the setup alert; ``...`` means the alert no longer exists.""" + expectation = update_expectation(item) + assert expectation is not None + before = _stored(expectation.setup_alert) + after = None if isinstance(edit, EllipsisType) else _stored(expectation.setup_alert, edit) + return evaluate_update( + expectation, before=before, after=after, update_called=update_called, alert_created=alert_created + ) + + +def _set(path: str, value: object) -> Edit: + def edit(entity: dict) -> None: + *parents, last = path.split(".") + node = entity + for key in parents: + node = node[key] if not key.isdigit() else node[int(key)] + node[last] = value + + return edit + + +# --- expectation --------------------------------------------------------------------------------- + + +def test_an_item_without_mode_is_not_an_update_item() -> None: + assert update_expectation({"operator": "LESS_THAN", "threshold": 1}) is None + + +def test_the_expectation_reads_display_keys_aliases_and_display_values() -> None: + expectation = update_expectation( + { + "mode": "Update", + "setup_alert": _COMPARISON_SETUP, + "expected_change": {"Trigger": "One time", "dashboard": "d2"}, + } + ) + assert expectation is not None + assert expectation.title == "Net Sales floor u1" + assert expectation.condition_kind == "comparison" + assert expectation.expected_change == {"trigger": "ONCE", "dashboard_id": "d2"} + + +def _without_title() -> dict: + setup = copy.deepcopy(_COMPARISON_SETUP) + del setup["attributes"]["title"] + return setup + + +def _two_conditions() -> dict: + setup = copy.deepcopy(_ANOMALY_SETUP) + setup["attributes"]["alert"]["condition"]["comparison"] = {"operator": "LESS_THAN"} + return setup + + +def _condition(condition: dict) -> dict: + setup = copy.deepcopy(_COMPARISON_SETUP) + setup["attributes"]["alert"]["condition"] = condition + return setup + + +def _with_attributes(**attributes: object) -> dict: + setup = copy.deepcopy(_COMPARISON_SETUP) + setup["attributes"] = {**setup["attributes"], **attributes} + return setup + + +@pytest.mark.parametrize( + ("item", "message"), + [ + ({"mode": "edit", "setup_alert": _COMPARISON_SETUP, "expected_change": {"threshold": 1}}, "mode must be"), + ({**_item(_COMPARISON_SETUP, threshold=1), "Threshold": 1}, "takes only"), + (_item(_COMPARISON_SETUP, cron="0 0 * * *"), "not a field update mode checks"), + (_item(_COMPARISON_SETUP), "at least one field"), + (_item(_ANOMALY_SETUP, threshold=1), "applies only to comparison and relative alerts"), + (_item(_COMPARISON_SETUP, sensitivity="LOW"), "applies only to anomaly alerts"), + (_item(_COMPARISON_SETUP, threshold="60k"), "must be a finite number"), + (_item(_COMPARISON_SETUP, threshold=True), "must be a finite number"), + (_item(_COMPARISON_SETUP, operator="INCREASES_BY"), "operator must be one of"), + (_item(_COMPARISON_SETUP, trigger="WEEKLY"), "trigger must be one of"), + (_item(_COMPARISON_SETUP, trigger_interval="WEEK"), "needs the ONCE_PER_INTERVAL trigger"), + (_item(_COMPARISON_SETUP, filters={"positiveAttributeFilter": {}}), "list of non-empty filter objects"), + (_item(_COMPARISON_SETUP, filters=[_LAST_MONTH, {}]), "list of non-empty filter objects"), + (_item(_COMPARISON_SETUP, threshold=float("nan")), "must be a finite number"), + (_item(_COMPARISON_SETUP, threshold=10**309), "must be a finite number"), + ({"Mode": None, "Setup alert": _COMPARISON_SETUP, "Expected change": {"threshold": 1}}, "mode must be"), + (_item(_COMPARISON_SETUP, title="A", name="B"), "names title twice"), + ({"mode": "update", "expected_change": {"threshold": 1}}, "must be an automation entity object"), + (_item(_without_title(), threshold=1), "title is required"), + (_item(_two_conditions(), sensitivity="LOW"), "exactly one alert condition"), + (_item({"attributes": _COMPARISON_SETUP["attributes"], "links": {}}, threshold=1), "only attributes and"), + (_item(_condition({"comparision": {"operator": "LESS_THAN"}}), title="T"), "condition must be one of"), + (_item(_condition({"comparison": "LESS_THAN 50000"}), title="T"), "comparison must be an object"), + (_item(["not", "an", "entity"], title="T"), "must be an automation entity object"), + (_item(_with_attributes(alert=None), title="T"), "attributes.alert is required"), + (_item({**_COMPARISON_SETUP, "relationships": ["metrics"]}, title="T"), "relationships must be an object"), + (_item({**_COMPARISON_SETUP, "relationships": []}, title="T"), "relationships must be an object"), + (_item(_COMPARISON_SETUP, title=" "), "title must be a non-empty string"), + ], +) +def test_a_malformed_update_item_raises_before_any_request(item: dict, message: str) -> None: + with pytest.raises(ValueError, match=message): + update_expectation(item) + + +def test_trigger_interval_is_accepted_together_with_the_once_per_interval_trigger() -> None: + expectation = update_expectation(_item(_COMPARISON_SETUP, trigger="ONCE_PER_INTERVAL", trigger_interval="week")) + assert expectation is not None + assert expectation.expected_change == {"trigger": "ONCE_PER_INTERVAL", "trigger_interval": "WEEK"} + + +def test_the_setup_is_sent_to_the_current_user_over_the_org_channel_unless_the_item_names_them() -> None: + expectation = update_expectation(_item(_COMPARISON_SETUP, threshold=60000)) + assert expectation is not None + entity = setup_entity(expectation, current_user_id="user-1", channel_id="defaultSmtp") + assert entity["relationships"]["recipients"] == {"data": [{"id": "user-1", "type": "user"}]} + assert entity["relationships"]["notificationChannel"] == { + "data": {"id": "defaultSmtp", "type": "notificationChannel"} + } + assert entity["relationships"]["analyticalDashboard"] == _COMPARISON_SETUP["relationships"]["analyticalDashboard"] + + named = copy.deepcopy(_COMPARISON_SETUP) + named["relationships"]["recipients"] = {"data": [{"id": "someone", "type": "user"}]} + named["relationships"]["notificationChannel"] = {"data": {"id": "smtp-2", "type": "notificationChannel"}} + expectation = update_expectation(_item(named, threshold=60000)) + assert expectation is not None + entity = setup_entity(expectation, current_user_id="user-1", channel_id="defaultSmtp") + assert entity["relationships"]["recipients"]["data"][0]["id"] == "someone" + assert entity["relationships"]["notificationChannel"]["data"]["id"] == "smtp-2" + + +# --- scoring ------------------------------------------------------------------------------------- + + +def test_a_threshold_update_that_changes_only_the_threshold_passes() -> None: + evaluation, changes = _evaluate( + _item(_COMPARISON_SETUP, threshold=60000), _set("attributes.alert.condition.comparison.right.value", 60000.0) + ) + assert evaluation.checks() == dict.fromkeys(evaluation.checks(), True) + assert changes == [] + + +def test_an_anomaly_update_that_wipes_the_metric_title_and_format_is_not_preserved() -> None: + # GDAI-2894: update_metric_alert rebuilt the anomaly measure with an empty title and format. + def wipe(entity: dict) -> None: + anomaly = entity["attributes"]["alert"]["condition"]["anomaly"] + anomaly["sensitivity"] = "LOW" + anomaly["measure"].update(title="", format="") + + evaluation, changes = _evaluate(_item(_ANOMALY_SETUP, sensitivity="LOW"), wipe) + assert evaluation.alert_update_correct is True + assert evaluation.alert_update_preserved is False + assert [c["path"] for c in changes] == [ + "attributes.alert.condition.anomaly.measure.format", + "attributes.alert.condition.anomaly.measure.title", + ] + assert changes[1] == { + "path": "attributes.alert.condition.anomaly.measure.title", + "before": "Net Sales", + "after": "", + } + + +def test_a_filter_update_may_rewrite_the_filter_metadata_but_must_keep_the_other_filter() -> None: + furniture = { + "positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "in": {"values": ["Furniture"]}} + } + + def swap(entity: dict) -> None: + entity["attributes"]["alert"]["execution"]["filters"][0] = { + "positiveAttributeFilter": {**furniture["positiveAttributeFilter"], "localIdentifier": "genai_vf1"} + } + entity["attributes"]["metadata"]["visibleFilters"][0]["title"] = "Category" + entity["relationships"]["labels"] = {"data": [{"id": "product_category", "type": "label"}]} + + item = _item(_COMPARISON_SETUP, filters=[_LAST_MONTH, furniture]) + evaluation, changes = _evaluate(item, swap) + assert evaluation.alert_update_correct is True + assert evaluation.alert_update_preserved is True + assert changes == [] + + def drop_the_date(entity: dict) -> None: + swap(entity) + del entity["attributes"]["alert"]["execution"]["filters"][1] + + evaluation, _ = _evaluate(item, drop_the_date) + assert evaluation.alert_update_correct is False + + +def test_the_selected_elements_of_a_filter_match_in_any_order() -> None: + def both(values: list[str]) -> dict: + return {"positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "in": {"values": values}}} + + item = _item(_COMPARISON_SETUP, filters=[both(["Clothing", "Furniture"]), _LAST_MONTH]) + stored = [{**both(["Furniture", "Clothing"]), "localIdentifier": "genai_vf1"}, _LAST_MONTH] + evaluation, _ = _evaluate(item, _set("attributes.alert.execution.filters", stored)) + assert evaluation.alert_update_correct is True + + evaluation, _ = _evaluate(item, _set("attributes.alert.execution.filters", [both(["Furniture"]), _LAST_MONTH])) + assert evaluation.alert_update_correct is False + + +def test_metadata_added_by_a_filter_update_is_compared_field_by_field() -> None: + bare = copy.deepcopy(_COMPARISON_SETUP) + del bare["attributes"]["metadata"] + furniture = { + "positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "in": {"values": ["Furniture"]}} + } + + def with_metadata(widget: bool) -> Edit: + def edit(entity: dict) -> None: + entity["attributes"]["alert"]["execution"]["filters"] = [furniture, _LAST_MONTH] + entity["attributes"]["metadata"] = {"visibleFilters": [{"localIdentifier": "genai_vf1"}]} + if widget: + entity["attributes"]["metadata"]["widget"] = "widget-net-sales" + + return edit + + item = _item(bare, filters=[furniture, _LAST_MONTH]) + evaluation, changes = _evaluate(item, with_metadata(widget=False)) + assert evaluation.strict_pass is True + assert changes == [] + _, changes = _evaluate(item, with_metadata(widget=True)) + assert changes == [{"path": "attributes.metadata.widget", "before": None, "after": "widget-net-sales"}] + + +def test_other_lists_in_a_filter_keep_their_order_and_dropped_metadata_is_reported_by_field() -> None: + top = {"rankingFilter": {"attributes": [{"localIdentifier": "a"}, {"localIdentifier": "b"}], "value": 3}} + flipped = {"rankingFilter": {"attributes": [{"localIdentifier": "b"}, {"localIdentifier": "a"}], "value": 3}} + item = _item(_COMPARISON_SETUP, filters=[top]) + evaluation, _ = _evaluate(item, _set("attributes.alert.execution.filters", [top])) + assert evaluation.alert_update_correct is True + evaluation, _ = _evaluate(item, _set("attributes.alert.execution.filters", [flipped])) + assert evaluation.alert_update_correct is False + + def raise_and_drop_metadata(entity: dict) -> None: + _RAISE(entity) + entity["attributes"]["metadata"] = None + + _, changes = _evaluate(_item(_COMPARISON_SETUP, threshold=60000), raise_and_drop_metadata) + assert [c["path"] for c in changes] == ["attributes.metadata.visibleFilters"] + + +def test_a_filter_update_does_not_own_the_widget_the_alert_was_set_on() -> None: + def swap_and_drop_the_widget(entity: dict) -> None: + entity["attributes"]["alert"]["execution"]["filters"][0]["positiveAttributeFilter"]["in"]["values"] = [ + "Furniture" + ] + entity["attributes"]["metadata"]["filters"] = ["genai_vf2"] + del entity["attributes"]["metadata"]["widget"] + + furniture = { + "positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "in": {"values": ["Furniture"]}} + } + setup = copy.deepcopy(_COMPARISON_SETUP) + setup["attributes"]["metadata"]["widget"] = "widget-net-sales" + evaluation, changes = _evaluate(_item(setup, filters=[furniture, _LAST_MONTH]), swap_and_drop_the_widget) + assert evaluation.alert_update_correct is True + assert evaluation.alert_update_preserved is False + assert changes == [{"path": "attributes.metadata.widget", "before": "widget-net-sales", "after": None}] + + +def test_an_unasked_change_elsewhere_fails_preserved_but_bookkeeping_does_not() -> None: + def also_move(entity: dict) -> None: + entity["attributes"]["alert"]["condition"]["comparison"]["right"]["value"] = 60000 + entity["attributes"]["description"] = "Alert when net_sales LESS_THAN 60000" + entity["relationships"]["analyticalDashboard"]["data"]["id"] = "dash-products" + + evaluation, changes = _evaluate(_item(_COMPARISON_SETUP, threshold=60000), also_move) + assert evaluation.alert_update_correct is True + assert evaluation.alert_update_preserved is False + assert [c["path"] for c in changes] == ["relationships.analyticalDashboard.data.id"] + + +def test_a_trigger_change_may_clear_the_interval_and_a_relative_threshold_is_read_from_its_own_place() -> None: + weekly = copy.deepcopy(_COMPARISON_SETUP) + weekly["attributes"]["alert"].update(trigger="ONCE_PER_INTERVAL", interval="WEEK") + + def to_once(entity: dict) -> None: + entity["attributes"]["alert"]["trigger"] = "ONCE" + del entity["attributes"]["alert"]["interval"] + + evaluation, _ = _evaluate(_item(weekly, trigger="ONCE"), to_once) + assert evaluation.strict_pass is True + + evaluation, _ = _evaluate( + _item(_RELATIVE_SETUP, threshold=0.15), _set("attributes.alert.condition.relative.threshold.value", 0.15) + ) + assert evaluation.strict_pass is True + + +def test_a_trigger_that_stays_once_per_interval_must_keep_the_interval() -> None: + weekly = copy.deepcopy(_COMPARISON_SETUP) + weekly["attributes"]["alert"].update(trigger="ONCE_PER_INTERVAL", interval="WEEK") + evaluation, changes = _evaluate( + _item(weekly, trigger="ONCE_PER_INTERVAL"), _set("attributes.alert.interval", "DAY") + ) + assert evaluation.alert_update_preserved is False + assert changes == [{"path": "attributes.alert.interval", "before": "WEEK", "after": "DAY"}] + + +def test_a_trigger_that_enters_once_per_interval_may_set_an_interval() -> None: + def to_daily(entity: dict) -> None: + entity["attributes"]["alert"].update(trigger="ONCE_PER_INTERVAL", interval="DAY") + + evaluation, _ = _evaluate(_item(_COMPARISON_SETUP, trigger="ONCE_PER_INTERVAL"), to_daily) + assert evaluation.strict_pass is True + + +def test_an_operator_and_a_dashboard_change_are_read_from_the_stored_alert() -> None: + def move(entity: dict) -> None: + entity["attributes"]["alert"]["condition"]["comparison"]["operator"] = "LESS_THAN_OR_EQUAL_TO" + entity["relationships"]["analyticalDashboard"]["data"]["id"] = "dash-products" + + item = _item(_COMPARISON_SETUP, operator="less_than_or_equal_to", dashboard="dash-products") + evaluation, _ = _evaluate(item, move) + assert evaluation.strict_pass is True + + def unlink(entity: dict) -> None: + move(entity) + entity["relationships"]["analyticalDashboard"] = "dash-products" + + evaluation, _ = _evaluate(item, unlink) + assert evaluation.alert_update_correct is False + + +def test_a_filter_list_with_a_filter_nobody_asked_for_is_not_the_expected_one() -> None: + def replace_the_date(entity: dict) -> None: + entity["attributes"]["alert"]["execution"]["filters"][1] = {"relativeDateFilter": {"granularity": "YEAR"}} + + evaluation, _ = _evaluate(_item(_COMPARISON_SETUP, filters=[_CATEGORY_FILTER, _LAST_MONTH]), replace_the_date) + assert evaluation.alert_update_correct is False + + +@pytest.mark.parametrize("stored_order", [("a", "b"), ("b", "a")]) +def test_an_expected_filter_that_fits_several_stored_ones_does_not_take_the_one_another_needs( + stored_order: tuple[str, str], +) -> None: + def with_id(local_id: str) -> dict: + return {"positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "localIdentifier": local_id}} + + stored = [with_id(f"genai_vf_{x}") for x in stored_order] + item = _item(_COMPARISON_SETUP, filters=[_CATEGORY_FILTER, with_id("genai_vf_a")]) + evaluation, _ = _evaluate(item, _set("attributes.alert.execution.filters", stored)) + assert evaluation.alert_update_correct is True + + +def test_an_alert_that_no_longer_exists_fails_every_check_but_the_call() -> None: + evaluation, changes = _evaluate(_item(_COMPARISON_SETUP, threshold=60000), ...) + assert evaluation.checks() == { + "alert_update_called": True, + "alert_update_correct": False, + "alert_update_preserved": False, + "alert_not_recreated": False, + } + assert changes == [] + + +def test_without_a_successful_update_call_only_that_check_is_named() -> None: + evaluation, _ = _evaluate(_item(_COMPARISON_SETUP, threshold=60000), None, update_called=False) + assert evaluation.alert_update_correct is False + assert evaluation.alert_update_preserved is False + run = MagicMock(eval=evaluation) + assert _failed_checks(run) == [{"name": "alert_update_called"}] + + +def test_a_created_alert_fails_not_recreated() -> None: + evaluation, _ = _evaluate( + _item(_COMPARISON_SETUP, threshold=60000), + _set("attributes.alert.condition.comparison.right.value", 60000), + alert_created=True, + ) + assert evaluation.alert_not_recreated is False + + +@pytest.mark.parametrize( + ("args", "expected"), + [ + ({"automation_id": "a1", "threshold": 1}, True), + ({"automation_ids": ["a1"], "state": "pause"}, True), + ({"automation_ids": "a1", "state": "pause"}, True), + ({"automation_id": "a2"}, False), + ({"automation_ids": ["a2"]}, False), + ({"automation_ids": '["a0", "a1"]'}, True), + ({"automation_ids": '["a2"]'}, False), + ({"automation_ids": "[a1"}, False), + ], +) +def test_an_update_call_targets_the_alert_by_id_or_id_list(args: dict, expected: bool) -> None: + assert targets_alert(args, "a1") is expected + + +def _event(tool: str, arguments: str, result: str | None) -> ToolCallEvent: + return ToolCallEvent.model_validate({"functionName": tool, "functionArguments": arguments, "result": result}) + + +def test_an_update_call_without_object_arguments_or_without_a_result_is_not_a_successful_update() -> None: + ok = '{"data": {"id": "a1"}}' + events = [ + _event("update_metric_alert", '["a1"]', ok), + _event("update_metric_alert", '{"automation_id": "a1", "threshold": 2}', None), + ] + args, updated = _update_calls(events, "a1") + assert updated is False + assert args == [ + {"tool": "update_metric_alert", "arguments": ["a1"]}, + {"tool": "update_metric_alert", "automation_id": "a1", "threshold": 2}, + ] + _, updated = _update_calls([*events, _event("update_metric_alert", '{"automation_id": "a1"}', ok)], "a1") + assert updated is True + + +def test_the_update_scores_are_conditional_scores() -> None: + assert set(AlertUpdateEvaluation(True, True, True, True).checks()) <= set(ALERT_CONDITIONAL_SCORES) + + +# --- runner -------------------------------------------------------------------------------------- + + +def _call(tool: str, args: dict, result: str | None = '{"data": {"id": "eval-1"}}') -> dict: + return {"functionName": tool, "functionArguments": json.dumps(args), "result": result} + + +def _turn(*calls: dict, text: str = "Done.") -> ChatResult: + return ChatResult.model_validate({"text_response": text, "toolCallEvents": list(calls)}) + + +_STATE_ERROR = ( + '{"data": {"isError": true, "error": {"text": "1 validation error for ArrayParameter\\nvalue\\n Value error"}}}' +) + + +def _fakes( + item: dict, + *turns: ChatResult | ChatError, + edit: Edit | None = None, + stale: tuple[str, ...] = (), + readable: bool = True, +) -> tuple[MagicMock, MagicMock]: + """A fake automation API holding the setup alert before the question and after it, and a chat client.""" + expectation = update_expectation(item) + assert expectation is not None + api = MagicMock() + api.create.return_value = "eval-1" + api.ids_titled.return_value = list(stale) + api.first_channel_id.return_value = "defaultSmtp" + before = _stored(expectation.setup_alert) if readable else None + api.get.side_effect = [before, _stored(expectation.setup_alert, edit)] + client = MagicMock() + client.send_message.side_effect = list(turns) + client.create_conversation.return_value = "conv-new" + return api, client + + +def _run( + item: dict, + *turns: ChatResult | ChatError, + edit: Edit | None = None, + max_iterations: int = 3, + stale: tuple[str, ...] = (), + fakes: tuple[MagicMock, MagicMock] | None = None, + conversation_id: str | None = "conv-1", + sim_error: Exception | None = None, + user_id: str | None = "user-1", + delete_metric: MagicMock | None = None, + automation_ids: list[set[str] | None] | None = None, +) -> tuple[AlertRunResult, MagicMock, MagicMock, MagicMock]: + """Run an update item over these agent turns against a fake automation API. + + Returns the run, the fake API, the chat client mock and the simulated user mock. + """ + api, client = fakes or _fakes(item, *turns, edit=edit, stale=stale) + sim_reply = {"side_effect": sim_error} if sim_error else {"return_value": "Yes, please apply that change."} + with ( + patch("gooddata_eval.core.agentic.alert_skill.ChatClient", return_value=client), + patch("gooddata_eval.core.agentic.alert_skill.AutomationApi", return_value=api), + patch("gooddata_eval.core.agentic.alert_skill._resolve_current_user_id", return_value=user_id), + patch("gooddata_eval.core.agentic.alert_skill.GoodDataSdk"), + patch("gooddata_eval.core.agentic.alert_skill._delete_metric", delete_metric or MagicMock()), + patch("gooddata_eval.core.agentic.alert_skill._automation_ids", side_effect=automation_ids or [None, None]), + patch("gooddata_eval.core.agentic.alert_skill.generate_simulated_update_response", **sim_reply) as sim, + ): + summary = run_agentic_alert_skill( + host="http://host", + token="tok", + workspace_id="ws1", + question='Raise the threshold of my "Net Sales floor u1" alert to $60,000.', + expected_output=item, + k=1, + max_iterations=max_iterations, + initial_conversation_id=conversation_id, + ) + return summary.best, api, client, sim + + +_RAISE = _set("attributes.alert.condition.comparison.right.value", 60000.0) + + +def test_an_update_in_the_first_turn_is_scored_and_the_setup_alert_is_deleted() -> None: + run, api, client, sim = _run( + _item(_COMPARISON_SETUP, threshold=60000), + _turn( + _call("list_automations", {}), _call("update_metric_alert", {"automation_id": "eval-1", "threshold": 60000}) + ), + edit=_RAISE, + stale=("eval-update-left-over",), + ) + assert run.eval.strict_pass is True + assert run.exit_reason == LoopExit.SUCCESS + assert run.actual_alert_arguments == { + "update_calls": [{"tool": "update_metric_alert", "automation_id": "eval-1", "threshold": 60000}], + "unexpected_changes": [], + } + created = api.create.call_args.args[0] + assert created["relationships"]["recipients"] == {"data": [{"id": "user-1", "type": "user"}]} + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-update-left-over", "eval-1"] + assert api.delete.call_args_list[0].kwargs == {"strict": True} + assert client.send_message.call_count == 1 + sim.assert_not_called() + + +def test_a_failed_state_call_followed_by_a_retry_counts_as_called() -> None: + def pause(entity: dict) -> None: + entity["attributes"]["state"] = "PAUSED" + + run, _, client, sim = _run( + _item(_COMPARISON_SETUP, state="PAUSED"), + _turn( + _call("update_alert_state", {"automation_ids": "eval-1", "state": "pause"}, _STATE_ERROR), + text="The alert could not be paused. Should I try again?", + ), + _turn( + _call( + "update_alert_state", + {"automation_ids": ["eval-1"], "state": "pause"}, + '{"data": {"paused_ids": ["eval-1"]}}', + ), + ), + edit=pause, + ) + # The failed call alone does not end the run as a success: the agent gets the next turn and retries. + assert client.send_message.call_count == 2 + assert sim.call_count == 1 + assert run.eval.strict_pass is True + + +def test_the_simulated_user_confirms_and_the_update_in_the_next_turn_counts() -> None: + run, _, client, sim = _run( + _item(_COMPARISON_SETUP, threshold=60000), + _turn(text="Should I raise the threshold of Net Sales floor u1 to 60,000?"), + _turn(_call("update_metric_alert", {"automation_id": "eval-1", "threshold": 60000})), + edit=_RAISE, + ) + assert run.eval.strict_pass is True + assert run.turns_used == 2 + assert sim.call_count == 1 + assert client.send_message.call_args_list[1].args == ("conv-1", "Yes, please apply that change.") + + +def test_a_new_alert_instead_of_an_update_fails_and_is_deleted_too() -> None: + run, api, *_ = _run( + _item(_COMPARISON_SETUP, threshold=60000), + _turn(_call("create_metric_alert", {"operator": "LESS_THAN", "threshold": 60000}, '{"id": "new-alert"}')), + max_iterations=1, + ) + assert run.eval.alert_update_called is False + assert run.eval.alert_not_recreated is False + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-1", "new-alert"] + + +# --- automation API ------------------------------------------------------------------------------ + + +def _api(handler: Callable[[httpx.Request], httpx.Response]) -> AutomationApi: + return AutomationApi("http://host/", "tok", "ws1", transport=httpx.MockTransport(handler)) + + +def test_the_api_creates_the_setup_alert_under_a_fresh_id_and_reads_it_back() -> None: + sent: list[dict] = [] + + def handler(request: httpx.Request) -> httpx.Response: + assert request.headers["Authorization"] == "Bearer tok" + if request.method == "POST": + sent.append(json.loads(request.content)) + return httpx.Response(201, json={}) + if request.url.path.endswith("/missing"): + return httpx.Response(404) + data = {"id": "x", "attributes": {"title": "T"}, "relationships": {"metrics": {}}, "links": {}} + return httpx.Response(200, json={"data": data}) + + api = _api(handler) + alert_id = api.create({"attributes": {"title": "T"}, "relationships": {}}) + assert alert_id.startswith("eval-update-") + assert sent == [{"data": {"id": alert_id, "type": "automation", "attributes": {"title": "T"}, "relationships": {}}}] + assert api.get(alert_id) == {"attributes": {"title": "T"}, "relationships": {"metrics": {}}} + assert api.get("missing") is None + api.close() + + +def test_the_api_finds_alerts_by_title_across_pages_and_picks_the_lowest_channel_id() -> None: + def handler(request: httpx.Request) -> httpx.Response: + if "notificationChannels" in request.url.path: + return httpx.Response(200, json={"data": [{"id": "smtp-b"}, {"id": "smtp-a"}]}) + page = int(request.url.params["page"]) + titles = ["Other"] * 249 + ["T"] if page == 0 else ["T"] + return httpx.Response( + 200, json={"data": [{"id": f"p{page}-{i}", "attributes": {"title": t}} for i, t in enumerate(titles)]} + ) + + api = _api(handler) + assert api.ids_titled("T") == ["p0-249", "p1-0"] + assert api.first_channel_id() == "smtp-a" + + +def test_the_lowest_channel_id_is_taken_across_pages() -> None: + def handler(request: httpx.Request) -> httpx.Response: + page = int(request.url.params["page"]) + ids = [f"smtp-{i:03d}" for i in range(1, 251)] if page == 0 else ["smtp-000"] + return httpx.Response(200, json={"data": [{"id": i} for i in ids]}) + + assert _api(handler).first_channel_id() == "smtp-000" + + +def test_a_strict_delete_raises_a_failure_but_not_a_missing_alert() -> None: + statuses = iter([404, 500]) + api = _api(lambda request: httpx.Response(next(statuses))) + api.delete("gone", strict=True) + with pytest.raises(httpx.HTTPStatusError): + api.delete("broken", strict=True) + + +def test_a_delete_ignores_a_missing_alert_and_logs_a_failure(capsys: pytest.CaptureFixture[str]) -> None: + statuses = iter([404, 500]) + api = _api(lambda request: httpx.Response(next(statuses))) + api.delete("gone") + api.delete("broken") + assert "Failed to delete alert broken" in capsys.readouterr().out + + +def test_a_broken_stream_after_a_successful_update_still_scores_it() -> None: + partial = _turn(_call("update_metric_alert", {"automation_id": "eval-1", "threshold": 60000})) + run, api, *_ = _run( + _item(_COMPARISON_SETUP, threshold=60000), ChatError("stream broke", partial_result=partial), edit=_RAISE + ) + assert run.eval.strict_pass is True + assert run.exit_reason != LoopExit.SUCCESS + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-1"] + + +def test_a_silent_turn_ends_the_run_without_asking_the_simulated_user() -> None: + run, _, client, sim = _run(_item(_COMPARISON_SETUP, threshold=60000), _turn(text="")) + assert run.exit_reason == LoopExit.AGENT_SILENT + assert run.eval.alert_update_called is False + assert client.send_message.call_count == 1 + sim.assert_not_called() + + +def test_a_run_in_its_own_conversation_deletes_it_and_the_metric_the_agent_created() -> None: + delete_metric = MagicMock() + run, _, client, _ = _run( + _item(_COMPARISON_SETUP, threshold=60000), + _turn( + _call("create_metric", {"title": "Net Sales copy"}, '{"data": {"metric_id": "m-new"}}'), + _call("update_metric_alert", {"automation_id": "eval-1", "threshold": 60000}), + ), + edit=_RAISE, + conversation_id=None, + delete_metric=delete_metric, + ) + assert run.conversation_id == "conv-new" + client.delete_conversation.assert_called_once_with("conv-new") + assert delete_metric.call_args.args[1:] == ("ws1", "m-new") + + +def test_a_failed_simulated_reply_ends_only_that_run() -> None: + run, *_ = _run( + _item(_COMPARISON_SETUP, threshold=60000), + _turn(text="Should I raise it to 60,000?"), + sim_error=RuntimeError("openai down"), + ) + assert run.exit_reason == LoopExit.SIMULATED_USER_FAILED + assert run.eval.alert_update_called is False + + +def test_a_setup_alert_that_cannot_be_read_back_raises_and_is_deleted() -> None: + item = _item(_COMPARISON_SETUP, threshold=60000) + api, client = _fakes(item, readable=False) + with pytest.raises(RuntimeError, match="cannot be read back"): + _run(item, fakes=(api, client)) + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-1"] + client.close.assert_called_once() + api.close.assert_called_once() + + +def test_an_update_item_needs_the_token_owner() -> None: + with pytest.raises(RuntimeError, match="user id could not be resolved"): + _run(_item(_COMPARISON_SETUP, threshold=60000), user_id=None) + + +def test_the_simulated_update_reply_asks_gpt_with_the_alert_title() -> None: + expectation = update_expectation(_item(_COMPARISON_SETUP, threshold=60000)) + assert expectation is not None + fake_openai = MagicMock() + fake_openai.return_value.chat.completions.create.return_value = MagicMock( + choices=[MagicMock(message=MagicMock(content="Yes, please apply that change."))] + ) + with ( + patch("gooddata_eval.core.agentic.alert_skill._OpenAI", fake_openai), + patch.dict("os.environ", {"OPENAI_API_KEY": "test-key"}), + ): + reply = generate_simulated_update_response("Apply it?", expectation, [], "Raise it to 60,000.") + assert reply == "Yes, please apply that change." + prompt = fake_openai.return_value.chat.completions.create.call_args.kwargs["messages"][0]["content"] + assert prompt == update_sim_user_prompt("Raise it to 60,000.", "Net Sales floor u1") + assert 'titled "Net Sales floor u1"' in prompt + + +def test_the_simulated_update_reply_needs_openai_and_its_key() -> None: + expectation = update_expectation(_item(_COMPARISON_SETUP, threshold=60000)) + assert expectation is not None + with ( + patch("gooddata_eval.core.agentic.alert_skill._OpenAI", None), + pytest.raises(RuntimeError, match="openai package is required"), + ): + generate_simulated_update_response("Apply it?", expectation, [], "Raise it.") + with ( + patch("gooddata_eval.core.agentic.alert_skill._OpenAI", MagicMock()), + patch.dict("os.environ", {"OPENAI_API_KEY": ""}), + pytest.raises(OSError, match="OPENAI_API_KEY"), + ): + generate_simulated_update_response("Apply it?", expectation, [], "Raise it.") + + +def test_a_failed_create_deletes_the_generated_id_and_raises_the_original_error() -> None: + posted: list[str] = [] + deleted: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST": + posted.append(json.loads(request.content)["data"]["id"]) + return httpx.Response(502) + deleted.append(request.url.path.rsplit("/", 1)[-1]) + return httpx.Response(500) + + api = _api(handler) + # The cleanup DELETE fails too; the POST's error is the one raised. + with pytest.raises(httpx.HTTPStatusError, match="502"): + api.create({"attributes": {"title": "T"}, "relationships": {}}) + assert len(posted) == 1 + assert deleted == posted + + +def test_an_alert_created_without_a_result_in_a_broken_stream_is_found_by_its_named_id_and_deleted() -> None: + partial = _turn(_call("create_metric_alert", {"automation_id": "net-sales-below", "threshold": 60000}, None)) + run, api, *_ = _run( + _item(_COMPARISON_SETUP, threshold=60000), + ChatError("stream broke", partial_result=partial), + automation_ids=[{"other-alert"}, {"other-alert", "eval-1", "net-sales-below"}], + ) + assert run.eval.alert_update_called is False + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-1", "net-sales-below"] + + +def test_a_named_id_is_not_deleted_without_a_listing_before_the_run() -> None: + partial = _turn(_call("create_metric_alert", {"automation_id": "other-alert"}, None)) + _, api, *_ = _run( + _item(_COMPARISON_SETUP, threshold=60000), + ChatError("stream broke", partial_result=partial), + automation_ids=[None, {"other-alert", "eval-1"}], + ) + assert [c.args[0] for c in api.delete.call_args_list] == ["eval-1"] + + +@pytest.mark.parametrize( + ("body", "call"), + [ + (["not", "an", "object"], lambda api: api.get("eval-1")), + ({"data": None}, lambda api: api.get("eval-1")), + ({"data": {"id": "eval-1"}}, lambda api: api.ids_titled("T")), + ({"data": [{"title": "no id"}]}, lambda api: api.first_channel_id()), + ({"data": {"id": "eval-1", "attributes": ["bad"]}}, lambda api: api.get("eval-1")), + ({"data": {"id": "eval-1", "attributes": {}, "relationships": ["bad"]}}, lambda api: api.get("eval-1")), + ], +) +def test_a_malformed_api_response_raises_at_the_boundary(body: object, call: Callable[[AutomationApi], object]) -> None: + api = _api(lambda request: httpx.Response(200, json=body)) + with pytest.raises(ValueError, match="JSON object|no data|no attributes"): + call(api) + + +def test_a_same_titled_alert_no_evaluation_created_stops_the_item_without_deleting_it() -> None: + item = _item(_COMPARISON_SETUP, threshold=60000) + api, client = _fakes(item, stale=("users-own-alert", "eval-update-left-over")) + with pytest.raises(RuntimeError, match="that no evaluation created: \\['users-own-alert'\\]"): + _run(item, fakes=(api, client)) + api.delete.assert_not_called() + api.create.assert_not_called() + + +def test_a_stale_setup_alert_that_cannot_be_deleted_stops_the_run_before_a_second_one_is_created() -> None: + item = _item(_COMPARISON_SETUP, threshold=60000) + api, client = _fakes(item, stale=("eval-update-left-over",)) + api.delete.side_effect = RuntimeError("500 Internal Server Error") + with pytest.raises(RuntimeError, match="500"): + _run(item, fakes=(api, client)) + api.create.assert_not_called() + + +def test_an_update_whose_result_is_not_an_object_is_not_a_successful_update() -> None: + _, updated = _update_calls([_event("update_metric_alert", '{"automation_id": "a1"}', "false")], "a1") + assert updated is False + + +def test_overlapping_filters_are_matched_without_trying_every_order() -> None: + many = [ + {"positiveAttributeFilter": {**_CATEGORY_FILTER["positiveAttributeFilter"], "localIdentifier": f"vf{i}"}} + for i in range(12) + ] + expected = [_CATEGORY_FILTER] * 11 + [_LAST_MONTH] + evaluation, _ = _evaluate( + _item(_COMPARISON_SETUP, filters=expected), _set("attributes.alert.execution.filters", many) + ) + assert evaluation.alert_update_correct is False