From 3001fd59093d7d1dc1c2961763696e90e17a8b44 Mon Sep 17 00:00:00 2001 From: huyenthanh09 Date: Mon, 23 Nov 2026 18:12:28 +0700 Subject: [PATCH] fix(gooddata-eval): show alert proposal filters, score created alerts only - render_alert_proposal keeps the proposal's filters (alert.execution.filters) and drops the measures and group-bys, so the simulated user can check the filters rule 3 asks it to check - Every create_metric_alert call of a turn is read, not only the first: a call whose result is an MCP isError or gen-ai's {"success": false} created nothing, the run is scored on the first call that did not fail and reports that call's alert id, and every created alert is deleted after the run - A turn whose calls all failed does not end the run: the agent gets the next turn to recover, and a run that never creates one scores alert_created=False instead of grading a failed call's arguments - A turn with no text after every call failed ends the run as agent_silent instead of asking the simulated user to answer nothing jira: QA-29886 risk: low Co-Authored-By: Claude Opus 5.5 --- .../gooddata_eval/core/agentic/alert_skill.py | 150 ++++++++++----- .../core/evaluators/alert_skill.py | 2 +- .../src/gooddata_eval/core/models.py | 3 +- .../tests/test_agentic_alert_skill.py | 180 ++++++++++++++++++ 4 files changed, 289 insertions(+), 46 deletions(-) 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 5771a621d..c6fc75542 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 @@ -919,20 +919,70 @@ def _normalize_expected_output(expected: dict) -> CatalogMetricAlert: ) -def _extract_alert_call(tool_call_events: list[ToolCallEvent]) -> tuple[str | None, dict, bool]: - """Return (alert_id, args, tool_called). tool_called=True whenever create_metric_alert appears.""" +def _alert_call_failed(result: dict | None) -> bool: + """Whether a ``create_metric_alert`` result reports an error, so the call created nothing. + + An MCP error carries ``isError``. gen-ai's tool registry reports rejected arguments and a + failed execution as ``{"success": false, "error": ...}`` instead, with no ``isError``. + """ + if not isinstance(result, dict): + return False + data = result.get("data") + payloads = [result, data] if isinstance(data, dict) else [result] + return any(p.get("isError") or p.get("success") is False for p in payloads) + + +def _created_alert_id(result: dict | None) -> str | None: + """Server-assigned id of the automation a call created: it lives in the result, not the arguments.""" + if not isinstance(result, dict): + return None + data = result.get("data") + alert_id = result.get("id") or (data.get("id") if isinstance(data, dict) else None) + return alert_id if isinstance(alert_id, str) and alert_id else None + + +@dataclass +class _AlertCalls: + """Every ``create_metric_alert`` call of a turn, read for scoring and for cleanup.""" + + called: bool = False + """The agent called the tool at least once.""" + created: bool = False + """At least one call did not report an error.""" + created_ids: list[str] = field(default_factory=list) + """Ids of every alert the calls created; each one is deleted after the run.""" + args: dict = field(default_factory=dict) + """Arguments of the first call that did not fail, else of the last call.""" + alert_id: str | None = None + """Id of the alert the call in ``args`` created, None when that call failed or its result has no id.""" + + +def _extract_alert_calls(tool_call_events: list[ToolCallEvent]) -> _AlertCalls: + """Read every ``create_metric_alert`` call, not only the first. + + The agent may retry after an error. Reading only the first call scored the arguments of a + call that failed and missed the id of the retry that succeeded, so that alert leaked into + the workspace (QA-29886). The run is scored on the first call that did not fail, which is + the first call whenever none failed, as before. + """ + calls = _AlertCalls() for tc in tool_call_events: - if tc.function_name == "create_metric_alert": - args = tc.parsed_arguments() or {} - alert_id: str | None = None - if tc.result: - try: - result_data = json.loads(tc.result) - alert_id = result_data.get("id") or (result_data.get("data") or {}).get("id") - except Exception: - pass - return alert_id, args, True - return None, {}, False + if tc.function_name != "create_metric_alert": + continue + calls.called = True + args = tc.parsed_arguments() or {} + result = tc.parsed_result() + if _alert_call_failed(result): + if not calls.created: + calls.args = args + continue + alert_id = _created_alert_id(result) + if alert_id is not None: + calls.created_ids.append(alert_id) + if not calls.created: + calls.created = True + calls.args, calls.alert_id = args, alert_id + return calls def render_alert_proposal(proposal: dict) -> str: @@ -940,16 +990,20 @@ def render_alert_proposal(proposal: dict) -> str: The alert skill's confirmation step deliberately emits no text part (GDAI-2032) — the prompt and the CTA live only in the proposal payload, which the frontend renders as a - widget. Dumping the payload (rather than prose) keeps recipients, condition, trigger and - dashboard visible so the simulated user can still verify them against its goal, and does - not need updating whenever ``AlertProposal`` grows a field. + widget. Dumping the payload (rather than prose) keeps recipients, condition, trigger, + filters and dashboard visible so the simulated user can still verify them against its + goal, and does not need updating whenever ``AlertProposal`` grows a field. """ cta = proposal.get("cta") or "Should I create this alert?" summary = {k: v for k, v in proposal.items() if k != "cta"} alert = dict(summary.get("alert") or {}) - # The AFM execution block is opaque wire dicts — noise that would crowd out the fields - # the simulated user actually has to check. - alert.pop("execution", None) + # `execution` is the only place a proposal carries its filters, which rule 3 of the simulated + # user checks. Hoisting them keeps them visible (QA-29886). The rest stays out: the measures + # repeat `condition`, and the simulated user is told nothing about group-bys, so a date + # group-by would only read as a time window rule 5 tells it to refuse. + execution = alert.pop("execution", None) + if isinstance(execution, dict): + alert["filters"] = execution.get("filters") or [] if "alert" in summary: # Key off presence, not truthiness: an alert whose only key was `execution` must # still be replaced, otherwise the original (execution-bearing) dict survives. @@ -1002,12 +1056,12 @@ def run_agentic_alert_skill( sdk = GoodDataSdk.create(host, token) def _run_once(conv_id: str) -> AlertRunResult: - alert_id_to_delete: str | None = None + alert_ids_to_delete: list[str] = [] run_started = time.monotonic() try: alert_id: str | None = None actual_args: dict = {} - tool_called = False + alert_created = False reasoning_steps: list[str] = [] response_id: str | None = None all_tool_call_events: list[ToolCallEvent] = [] @@ -1036,7 +1090,7 @@ def _run_once(conv_id: str) -> AlertRunResult: # discarding every K-run already completed along with any exit_reason. print(f"[CHAT] send_message failed for conversation {conv_id}: {exc}") # The stream can break AFTER create_metric_alert already succeeded - # server-side. That id only ever reached alert_id_to_delete from the + # server-side. That id only ever reached alert_ids_to_delete from the # normal path below, so breaking here left the alert in the workspace for # the `finally` cleanup to miss -- a real object leaking out of a failed # run, not a reporting gap. @@ -1044,9 +1098,7 @@ def _run_once(conv_id: str) -> AlertRunResult: if partial is not None: reasoning_steps.extend(partial.reasoning_steps or []) response_id = partial.response_id or response_id - partial_alert_id, _, partial_tool_called = _extract_alert_call(partial.tool_call_events or []) - if partial_tool_called: - alert_id_to_delete = partial_alert_id + alert_ids_to_delete.extend(_extract_alert_calls(partial.tool_call_events or []).created_ids) exit_reason = chat_failure_exit(exc) break # `turns_used` counts attempts (set above, so a failed send still shows the @@ -1064,14 +1116,24 @@ def _run_once(conv_id: str) -> AlertRunResult: ) all_tool_call_events.extend(chat_result.tool_call_events or []) all_reasoning_step_events.extend(chat_result.reasoning_step_events or []) - alert_id, actual_args, tool_called = _extract_alert_call(chat_result.tool_call_events or []) - if tool_called: - alert_id_to_delete = alert_id + calls = _extract_alert_calls(chat_result.tool_call_events or []) + alert_ids_to_delete.extend(calls.created_ids) + if calls.created: + alert_id, actual_args = calls.alert_id, calls.args + alert_created = True exit_reason = LoopExit.SUCCESS break + if calls.called: + # Every call reported an error, so nothing was created. Scoring their arguments + # would pass a run whose creation failed, and ending here would label it a + # success. The agent gets the next turn to recover, as with a user, and the + # failed arguments are kept for triage. + actual_args = calls.args response_text = render_turn_for_simulated_user(chat_result) - # Stop if agent gave a completely empty response (stuck) - if not response_text and not chat_result.tool_call_events: + # Stop if the agent gave a completely empty response (stuck), or wrote nothing after + # every create call failed: the rendered turn holds no tool results, so the simulated + # user would be asked to answer an empty message. + if not response_text and (calls.called or not chat_result.tool_call_events): exit_reason = LoopExit.AGENT_SILENT break # Stop before generating a follow-up for the last iteration @@ -1100,23 +1162,23 @@ def _run_once(conv_id: str) -> AlertRunResult: current_question = follow_up ev = AlertEvaluation( - alert_created=tool_called, - operator_correct=tool_called and expected.operator == actual_args.get("operator"), - threshold_correct=tool_called and _check_threshold(expected, actual_args), - trigger_correct=tool_called and _check_trigger(expected, actual_args), - filters_correct=tool_called and _check_filters(expected, actual_args), - metric_correct=tool_called and _check_metric(expected, actual_args), - recipients_correct=tool_called + alert_created=alert_created, + operator_correct=alert_created and expected.operator == actual_args.get("operator"), + threshold_correct=alert_created and _check_threshold(expected, actual_args), + trigger_correct=alert_created and _check_trigger(expected, actual_args), + filters_correct=alert_created and _check_filters(expected, actual_args), + metric_correct=alert_created and _check_metric(expected, actual_args), + recipients_correct=alert_created and _check_recipients(expected, actual_args, sdk=sdk, current_user_id=current_user_id), - attributes_correct=tool_called and _check_attributes(expected, actual_args), - granularity_correct=tool_called and _check_granularity(expected, actual_args), + attributes_correct=alert_created and _check_attributes(expected, actual_args), + granularity_correct=alert_created and _check_granularity(expected, actual_args), comparison_correct=None if expected.comparison is None - else tool_called and _check_comparison(expected, actual_args), - title_correct=None if expected.title is None else tool_called and _check_title(expected, actual_args), + else alert_created and _check_comparison(expected, actual_args), + title_correct=None if expected.title is None else alert_created and _check_title(expected, actual_args), dashboard_correct=None if expected.dashboard_id is None - else tool_called and _check_dashboard(expected, actual_args), + else alert_created and _check_dashboard(expected, actual_args), ) return AlertRunResult( conversation_id=conv_id, @@ -1134,8 +1196,8 @@ def _run_once(conv_id: str) -> AlertRunResult: run_latency_s=time.monotonic() - run_started, ) finally: - if alert_id_to_delete: - _delete_alert(sdk, workspace_id, alert_id_to_delete) + for created_id in dict.fromkeys(alert_ids_to_delete): + _delete_alert(sdk, workspace_id, created_id) try: conv_id_0 = initial_conversation_id if initial_conversation_id is not None else client.create_conversation() diff --git a/packages/gooddata-eval/src/gooddata_eval/core/evaluators/alert_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/alert_skill.py index 0303af7c4..0b5326ca6 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/evaluators/alert_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/alert_skill.py @@ -28,7 +28,7 @@ def _extract_metric_id(metric_str: str) -> str | None: def _extract_automation_id(tool_event) -> str | None: """Real server-assigned id of the automation this call created. - Mirrors ``core/agentic/alert_skill.py``'s ``_extract_alert_call`` — the id + Mirrors ``core/agentic/alert_skill.py``'s ``_created_alert_id`` — the id lives in the tool *result* (what the server assigned), not the tool call *arguments* (what the agent asked for). """ diff --git a/packages/gooddata-eval/src/gooddata_eval/core/models.py b/packages/gooddata-eval/src/gooddata_eval/core/models.py index c1d920215..4737f8faf 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/models.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/models.py @@ -39,7 +39,8 @@ class LoopExit(str, Enum): """The agent produced the expected output; the loop broke early.""" AGENT_SILENT = "agent_silent" - """The agent returned neither text nor a tool call -- genuinely stuck.""" + """The agent returned neither text nor a tool call -- genuinely stuck. The alert skill also + ends here when the agent writes nothing after every ``create_metric_alert`` call failed.""" BUDGET_EXHAUSTED = "budget_exhausted" """The loop hit ``max_iterations`` without the agent producing its output. Says nothing diff --git a/packages/gooddata-eval/tests/test_agentic_alert_skill.py b/packages/gooddata-eval/tests/test_agentic_alert_skill.py index 1cc9ed31d..c85620c9c 100644 --- a/packages/gooddata-eval/tests/test_agentic_alert_skill.py +++ b/packages/gooddata-eval/tests/test_agentic_alert_skill.py @@ -1,5 +1,6 @@ # (C) 2026 GoodData Corporation. All rights reserved. # SPDX-License-Identifier: LicenseRef-GoodData-Enterprise +import json from contextlib import ExitStack, contextmanager from unittest.mock import MagicMock, patch @@ -7,6 +8,7 @@ from gooddata_eval.core.agentic._catalog import AnomalyDetectionGranularity from gooddata_eval.core.agentic.alert_skill import ( AlertEvaluation, + AlertRunResult, AlertSkillAssertionError, _check_attributes, _check_comparison, @@ -822,6 +824,184 @@ def test_render_alert_proposal_falls_back_to_default_cta(): assert render_alert_proposal({}).startswith("Should I create this alert?") +def test_render_alert_proposal_shows_filters_but_not_group_bys() -> None: + # Rule 3 asks the simulated user to check the filters, which live only in `execution`. It is told + # nothing about group-bys, and a date group-by would read as a time window, so they stay out. + proposal = { + "alert": { + "condition": {"comparison": {"operator": "LESS_THAN", "right": {"value": 1000}}}, + "execution": { + "measures": [{"opaque": "afm"}], + "attributes": [_AFM_MONTH_GROUPING], + "filters": [_DATE_FILTER, _ATTR_FILTER], + }, + } + } + rendered = render_alert_proposal(proposal) + assert "relativeDateFilter" in rendered + assert "United States" in rendered + assert "customer_created_date.month" not in rendered + assert "opaque" not in rendered + assert "execution" not in rendered + + +def test_render_alert_proposal_shows_that_there_are_no_filters() -> None: + rendered = render_alert_proposal({"alert": {"execution": {"measures": [{"opaque": "afm"}]}}}) + assert '"filters": []' in rendered + + +def _create_call(result: str | None, threshold: int = 500) -> dict: + return { + "functionName": "create_metric_alert", + "functionArguments": json.dumps({"operator": "GREATER_THAN", "threshold": threshold}), + "result": result, + } + + +_MCP_ERROR = '{"data": {"isError": true, "error": {"text": "Error calling tool \'create_metric_alert\'"}}}' +# gen-ai's tool registry reports rejected arguments and a failed execution this way, with no isError. +_REGISTRY_ERROR = ( + '{"success": false, "error": "Tool \'create_metric_alert\' execution failed due to an internal error."}' +) + + +def _turn(*calls: dict, text: str = "Done.") -> ChatResult: + return ChatResult.model_validate({"text_response": text, "toolCallEvents": list(calls)}) + + +def _run_turns(*turns: ChatResult | ChatError, max_iterations: int = 1) -> tuple[AlertRunResult, list[str]]: + """Run one alert conversation over these agent turns; returns the run and the alert ids it deleted. + + A ``ChatError`` among the turns is raised by that turn's send, as a broken stream is. + """ + client = MagicMock() + client.send_message.side_effect = list(turns) + with ( + _patched(client, simulated_reply="Please try again."), + patch("gooddata_eval.core.agentic.alert_skill._delete_alert") as mock_delete, + ): + summary = run_agentic_alert_skill( + host="http://host", + token="tok", + workspace_id="ws1", + question="Notify me whenever the number of orders goes above 500", + expected_output={"operator": "GREATER_THAN", "threshold": 500}, + k=1, + max_iterations=max_iterations, + initial_conversation_id="conv-1", + ) + return summary.best, [c.args[2] for c in mock_delete.call_args_list] + + +@pytest.mark.parametrize("error", [_MCP_ERROR, _REGISTRY_ERROR], ids=["mcp_error", "registry_error"]) +def test_retry_after_failed_create_scores_and_deletes_the_alert_it_created(error: str) -> None: + # The first call errored; reading only it leaked the retry's alert and scored failed arguments. + run, deleted = _run_turns(_turn(_create_call(error, threshold=1), _create_call('{"id": "alert-2"}'))) + assert run.eval.alert_created is True + assert run.eval.threshold_correct is True + assert run.alert_id == "alert-2" + assert deleted == ["alert-2"] + + +def test_a_failed_call_after_a_created_alert_does_not_replace_its_arguments() -> None: + run, deleted = _run_turns(_turn(_create_call('{"id": "alert-1"}'), _create_call(_REGISTRY_ERROR, threshold=1))) + assert run.eval.threshold_correct is True + assert run.alert_id == "alert-1" + assert deleted == ["alert-1"] + + +def test_the_first_created_alert_is_scored_and_every_one_is_deleted() -> None: + # As before QA-29886: when no call failed, the run is scored on the first one. + run, deleted = _run_turns( + _turn(_create_call('{"id": "alert-1"}'), _create_call('{"data": {"id": "alert-2"}}', threshold=7)) + ) + assert run.eval.threshold_correct is True + assert run.alert_id == "alert-1" + assert deleted == ["alert-1", "alert-2"] + + +def test_the_reported_alert_id_belongs_to_the_scored_call() -> None: + # A result without an id still counts as a created alert; the next call's id is not its id. + run, deleted = _run_turns(_turn(_create_call('{"status": "ok"}'), _create_call('{"id": "alert-2"}', threshold=7))) + assert run.eval.alert_created is True + assert run.actual_alert_arguments["threshold"] == 500 + assert run.alert_id is None + assert deleted == ["alert-2"] + + +def test_the_run_ends_when_the_agent_says_nothing_after_every_create_call_failed() -> None: + # The rendered turn holds no tool results, so the simulated user would answer an empty message. + client = MagicMock() + client.send_message.side_effect = [ + _turn(_create_call(_REGISTRY_ERROR), text=""), + _turn(_create_call('{"id": "alert-2"}')), + ] + with ( + _patched(client, simulated_reply="Please try again.") as mock_sim, + patch("gooddata_eval.core.agentic.alert_skill._delete_alert") as mock_delete, + ): + summary = run_agentic_alert_skill( + host="http://host", + token="tok", + workspace_id="ws1", + question="Notify me whenever the number of orders goes above 500", + expected_output={"operator": "GREATER_THAN", "threshold": 500}, + k=1, + max_iterations=2, + initial_conversation_id="conv-1", + ) + assert mock_sim is not None + mock_sim.assert_not_called() + assert client.send_message.call_count == 1 + assert summary.best.exit_reason == LoopExit.AGENT_SILENT + assert summary.best.eval.alert_created is False + mock_delete.assert_not_called() + + +@pytest.mark.parametrize("result", [None, "Alert created."], ids=["no_result", "not_json"]) +def test_a_create_call_whose_result_cannot_be_read_still_counts_as_created(result: str | None) -> None: + # Kept as before QA-29886: an unusual result shape must not turn into a false failure. + # Such a result carries no id, so there is nothing to delete. + run, deleted = _run_turns(_turn(_create_call(result))) + assert run.eval.alert_created is True + assert run.exit_reason == LoopExit.SUCCESS + assert run.alert_id is None + assert deleted == [] + + +def test_a_broken_stream_deletes_only_the_alerts_its_create_calls_created() -> None: + # The cleanup of the chat-error path reads every call too, not only the first: a failed call + # created nothing to delete, and its retry's alert must not leak. + partial = _turn(_create_call(_REGISTRY_ERROR, threshold=1), _create_call('{"id": "alert-2"}'), text="") + run, deleted = _run_turns(ChatError("stream died after create", partial_result=partial)) + assert run.exit_reason == LoopExit.CHAT_ERROR + assert run.eval.alert_created is False + assert deleted == ["alert-2"] + + +def test_create_calls_that_all_failed_create_no_alert() -> None: + run, deleted = _run_turns(_turn(_create_call(_MCP_ERROR), _create_call(_REGISTRY_ERROR, threshold=1))) + assert run.eval.alert_created is False + assert run.eval.strict_pass is False + assert run.exit_reason == LoopExit.BUDGET_EXHAUSTED + # Kept for triage, not scored. + assert run.actual_alert_arguments["threshold"] == 1 + assert deleted == [] + + +def test_the_agent_gets_a_turn_to_recover_after_every_create_call_failed() -> None: + run, deleted = _run_turns( + _turn(_create_call(_MCP_ERROR, threshold=1), text="The channel id was rejected. Should I try again?"), + _turn(_create_call('{"id": "alert-2"}')), + max_iterations=2, + ) + assert run.exit_reason == LoopExit.SUCCESS + assert run.total_turns == 2 + assert run.eval.threshold_correct is True + assert run.alert_id == "alert-2" + assert deleted == ["alert-2"] + + _QUESTIONS_PART = { "type": "clarifyingQuestions", "questions": [