From b2676898a717518b46eaca586ef23dd5b20413c4 Mon Sep 17 00:00:00 2001 From: huyenthanh09 Date: Fri, 27 Nov 2026 14:39:07 +0700 Subject: [PATCH] feat(gooddata-eval): opt-in per-field checks for KDA items - A KDA item with `check_fields: true` gates on six more checks besides completion: kda_measure_correct, kda_date_attribute_correct, kda_analyzed_period_correct, kda_reference_period_correct, kda_filters_correct and kda_summary_correct (KDA_FIELD_SCORES) - Filters compares the non-date filters only, in any order, with label/ and attribute/ ids equal. A date filter the agent adds is ignored; when it changes the numbers, the summary fails - Periods compare part by part, numbers as numbers (2024-1 = 2024-01) - Summary compares each stated value within absolute_tolerance (default 0.01), in decimal so the bound is inclusive; a string tolerance such as "1E-2" is read as a number - any_of lists complete alternatives; a run passes when one option matches all six fields, so one option's date never pairs with another option's summary. The simulated user answers from the first whole option - The execute call is paired with the create whose kda_ref it names; an execute naming a ref no create of the turn returned is not counted, and a create the tool rejected after an analysis ran does not replace it. Filters that are not a list fail the filters check. Tool arguments or results that are not a JSON object fail the run instead of crashing the item - A malformed item raises before the trace opens or any request: a missing field, an unknown key, `check fields` or `any of` spellings, a non-string date attribute, a measure type or aggregation the tool does not take, an attribute filter without one non-empty include/exclude list of strings - Items without the key score as before. The key keeps the gate off until the items opt in, whoever bumps the package - A failing run reports the expected and actual value of each field jira: QA-28699 risk: low Co-Authored-By: Claude Opus 5.5 --- packages/gooddata-eval/README.md | 52 ++ .../core/agentic/_kda_expectation.py | 365 ++++++++ .../gooddata_eval/core/agentic/kda_skill.py | 145 ++- .../tests/test_agentic_kda_skill_fields.py | 827 ++++++++++++++++++ 4 files changed, 1360 insertions(+), 29 deletions(-) create mode 100644 packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py create mode 100644 packages/gooddata-eval/tests/test_agentic_kda_skill_fields.py diff --git a/packages/gooddata-eval/README.md b/packages/gooddata-eval/README.md index 00ef71e95..cbb2047dd 100644 --- a/packages/gooddata-eval/README.md +++ b/packages/gooddata-eval/README.md @@ -1099,6 +1099,58 @@ the editors and the generated `description` are not compared) and `alert_not_rec (the alert still exists and the agent created none). A failing run reports the update arguments and every field that changed unasked. +### `agentic_kda_skill` field checks + +A KDA item is scored on completion: `kda_triggered`, `kda_executed`, `kda_success` and +`kda_turn_completed`. With `"check_fields": true` the run must also match every field of the +`create_key_driver_analysis` call and the summary its execution returns: + +```json +{ + "question": "What drove the change in Total Sales Amount in Q4 2024 versus Q3 2024, excluding the United States East region?", + "expected_output": { + "check_fields": true, + "Measure": {"id": "total_sales_amount_daily_store", "type": "metric"}, + "Date Attribute": "transaction_date.quarter", + "Analyzed Period": "2024-4", + "Reference Period": "2024-3", + "Filters": [ + {"type": "attribute_filter", "using": "label/dim_geography_region.region_name", "state": {"exclude": ["United States East"]}} + ], + "Summary": {"analyzed_value": 13868253.55, "reference_value": 15142121.31, "change": -1273867.76, "absolute_tolerance": 0.01} + } +} +``` + +| Score | Passes when | +|---|---| +| `kda_measure_correct` | the measure has the id and type of a `Measure` candidate (one object or a list), and its aggregation when the candidate states one | +| `kda_date_attribute_correct` | `date_attribute_id` equals `Date Attribute` | +| `kda_analyzed_period_correct`, `kda_reference_period_correct` | the period has the expected parts, numbers compared as numbers (`2024-1` is `2024-01`, `2024-Q3` is not `2024-3`) | +| `kda_filters_correct` | the non-date filters equal `Filters` in any order (`[]` for none). Date filters are not compared: the periods set the scope, and a date filter that changes the numbers fails the summary | +| `kda_summary_correct` | the execution succeeded and each of `analyzed_value`, `reference_value` and `change` the item states is within `absolute_tolerance` (default 0.01) | + +`any_of` lists complete alternatives for a question two answers fit. Each option replaces some +of the fields, and a run passes when one option matches all six. The summary depends on the +date attribute, so an option that changes one states both: + +```json +"any_of": [ + {"Date Attribute": "transaction_date.quarter", "Summary": {"analyzed_value": 184, "reference_value": 163}}, + {"Date Attribute": "return_date.quarter", "Summary": {"analyzed_value": 191, "reference_value": 156}} +] +``` + +A missing field, an unknown key, `check fields` or `any of` spelled with a space or capitals, a +measure type or aggregation the tool does not take, an attribute filter without one non-empty +`include` or `exclude` list of strings, a date filter in `Filters` or `any_of` without +`check_fields` is rejected before any request. The execute call is paired with the create whose +`kda_ref` it names; an execute naming a ref no create of the turn returned is not counted, and a +create the tool rejected after an analysis ran does not replace it. `filters` that are not a list +fail `kda_filters_correct`; omitted ones are no filters. The six names are `KDA_FIELD_SCORES`; a run that never called +create publishes none of them. A failing run reports the expected and the actual value of each +field it failed. + ### 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/_kda_expectation.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py new file mode 100644 index 000000000..843a1a5a4 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py @@ -0,0 +1,365 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""The KDA item's field checks: what ``create_key_driver_analysis`` and its execution must match. + +An item opts in with ``check_fields: true``. Its expected output then names the measure, the date +attribute, both periods, the non-date filters and the summary the execution must return. Without +the key, nothing here runs and the item is scored on completion only. + +``any_of`` lists complete alternatives. Each option replaces some fields of the item, and a run +passes when one option matches every field. The summary goes with the date attribute, so an +option that changes one usually states both. +""" + +from __future__ import annotations + +import json +import math +import re +from collections.abc import Mapping +from dataclasses import dataclass +from decimal import Decimal +from typing import Any + +# The fields in the order they are checked and published. Score ``kda__correct`` each. +KDA_FIELDS = ("measure", "date_attribute", "analyzed_period", "reference_period", "filters", "summary") +KDA_FIELD_SCORES = tuple(f"kda_{name}_correct" for name in KDA_FIELDS) + +_FIELD_KEYS = { + "measure": "Measure", + "date_attribute": "Date Attribute", + "analyzed_period": "Analyzed Period", + "reference_period": "Reference Period", + "filters": "Filters", + "summary": "Summary", +} +_OPTION_KEYS = frozenset(_FIELD_KEYS.values()) +_ITEM_KEYS = _OPTION_KEYS | {"check_fields", "any_of"} +_SUMMARY_VALUES = ("analyzed_value", "reference_value", "change") +_SUMMARY_KEYS = frozenset({*_SUMMARY_VALUES, "absolute_tolerance"}) +_DEFAULT_TOLERANCE = 0.01 +_MEASURE_KEYS = frozenset({"id", "type", "aggregation"}) +# The values create_key_driver_analysis accepts. It upper-cases the aggregation itself. +_MEASURE_TYPES = ("metric", "fact", "attribute") +_AGGREGATIONS = ("SUM", "AVG", "MIN", "MAX", "MEDIAN", "COUNT") +_FILTER_STATES = ("include", "exclude") +# Spelled like the item's other keys, these would leave the checks off without a word. +_OPT_IN_KEYS = ("check_fields", "any_of") +_DATE_FILTER = "date_filter" +# The agent's tools take an attribute by its label or its attribute id. Both ids are equal in the +# eval workspaces, so a filter is matched on the id alone. +_TYPE_PREFIXES = ("label/", "attribute/") + + +@dataclass(frozen=True) +class KdaFieldOption: + """One complete set of expected fields.""" + + measures: tuple[dict[str, Any], ...] + date_attribute: str + analyzed_period: str + reference_period: str + filters: tuple[Any, ...] + filter_entries: tuple[dict[str, Any], ...] + summary: dict[str, float] + tolerance: float + + +@dataclass(frozen=True) +class KdaExpectation: + """The item's field checks. ``options`` is empty when the item does not opt in.""" + + options: tuple[KdaFieldOption, ...] = () + + @property + def check_fields(self) -> bool: + return bool(self.options) + + +@dataclass(frozen=True) +class KdaFieldResult: + """The fields of one run, checked against the option that matched most of them.""" + + checks: dict[str, bool] + option_index: int + expected: dict[str, Any] + actual: dict[str, Any] + + @property + def passed(self) -> bool: + return all(self.checks.values()) + + +def _to_float(value: Any) -> float | None: + """A finite number from an int, float or numeric string, else None. A bool is not a number.""" + if isinstance(value, bool) or value is None: + return None + try: + number = float(str(value)) + except ValueError: + return None + return number if math.isfinite(number) else None + + +def _measures(value: Any) -> tuple[dict[str, Any], ...]: + candidates = value if isinstance(value, list) else [value] + if not candidates: + raise ValueError("Measure must name at least one candidate") + for candidate in candidates: + if not isinstance(candidate, dict) or not isinstance(candidate.get("id"), str) or not candidate["id"]: + raise ValueError(f"Measure candidate needs a non-empty string id, got {candidate!r}") + if candidate.get("type") not in _MEASURE_TYPES: + raise ValueError(f"Measure candidate type must be one of {', '.join(_MEASURE_TYPES)}, got {candidate!r}") + aggregation = candidate.get("aggregation") + if aggregation is not None and str(aggregation).upper() not in _AGGREGATIONS: + raise ValueError(f"Measure aggregation must be one of {', '.join(_AGGREGATIONS)}, got {candidate!r}") + if unknown := set(candidate) - _MEASURE_KEYS: + raise ValueError(f"Measure candidate has unknown keys {sorted(unknown)}, got {candidate!r}") + return tuple(candidates) + + +def _text(key: str, value: Any, *, allow_int: bool = False) -> str: + # A year period may be an int ("Analyzed Period": 2024); a date attribute id never is, and a bool is neither. + allowed = (str, int) if allow_int else str + if isinstance(value, bool) or not isinstance(value, allowed) or not str(value).strip(): + raise ValueError(f"{key} must be a non-empty string, got {value!r}") + return str(value).strip() + + +def _period_key(value: Any) -> tuple[int | str, ...]: + """A period by its parts, numbers as numbers: the tool reads ``2024-1`` and ``2024-01`` as one month.""" + return tuple(int(part) if part.isdigit() else part for part in re.split(r"[-\s:]+", str(value).strip())) + + +def _check_attribute_filter(entry: dict[str, Any]) -> None: + using, state = entry.get("using"), entry.get("state") + if not isinstance(using, str) or not using.strip(): + raise ValueError(f"attribute_filter needs a non-empty using, got {entry!r}") + if not isinstance(state, dict) or len(state) != 1 or next(iter(state)) not in _FILTER_STATES: + raise ValueError(f"attribute_filter state needs exactly one of include, exclude, got {entry!r}") + values = next(iter(state.values())) + if not isinstance(values, list) or not values or not all(isinstance(v, str) for v in values): + raise ValueError(f"attribute_filter {next(iter(state))} must be a non-empty list of strings, got {entry!r}") + + +def _filters(value: Any) -> tuple[Any, ...]: + if not isinstance(value, list): + raise ValueError(f"Filters must be a list, [] for none, got {value!r}") + for entry in value: + if not isinstance(entry, dict): + raise ValueError(f"Filters must hold objects, got {entry!r}") + if entry.get("type") == _DATE_FILTER: + raise ValueError("Filters must not hold a date_filter: date filters are not checked, the periods are") + if entry.get("type") == "attribute_filter": + _check_attribute_filter(entry) + return tuple(_filter_key(entry) for entry in value) + + +def _summary(value: Any) -> tuple[dict[str, float], float]: + if not isinstance(value, dict): + raise ValueError(f"Summary must be an object, got {value!r}") + if unknown := set(value) - _SUMMARY_KEYS: + raise ValueError(f"Summary has unknown keys {sorted(unknown)}") + numbers: dict[str, float] = {} + for key in _SUMMARY_VALUES: + if key in value: + number = _to_float(value[key]) + if number is None: + raise ValueError(f"Summary {key} must be a number, got {value[key]!r}") + numbers[key] = number + if not numbers: + raise ValueError(f"Summary must state at least one of {', '.join(_SUMMARY_VALUES)}") + tolerance = _to_float(value.get("absolute_tolerance", _DEFAULT_TOLERANCE)) + if tolerance is None or tolerance < 0: + raise ValueError(f"Summary absolute_tolerance must be a number >= 0, got {value.get('absolute_tolerance')!r}") + return numbers, tolerance + + +def _option(fields: Mapping[str, Any], label: str) -> KdaFieldOption: + if missing := [key for key in _FIELD_KEYS.values() if key not in fields]: + raise ValueError(f"{label} lacks {', '.join(missing)}: check_fields needs every field, Filters [] for none") + summary, tolerance = _summary(fields["Summary"]) + return KdaFieldOption( + measures=_measures(fields["Measure"]), + date_attribute=_text("Date Attribute", fields["Date Attribute"]), + analyzed_period=_text("Analyzed Period", fields["Analyzed Period"], allow_int=True), + reference_period=_text("Reference Period", fields["Reference Period"], allow_int=True), + filters=_filters(fields["Filters"]), + filter_entries=tuple(fields["Filters"]), + summary=summary, + tolerance=tolerance, + ) + + +def _reject_respelt_keys(expected: dict[str, Any]) -> None: + for key in expected: + canonical = re.sub(r"[\s-]+", "_", key.strip()).lower() if isinstance(key, str) else key + if canonical in _OPT_IN_KEYS and key != canonical: + raise ValueError(f"write {canonical!r}, not {key!r}") + + +def parse_kda_expectation(expected: Any) -> KdaExpectation: + """Read the item's field checks, raising ValueError on a malformed one before any request is sent.""" + if isinstance(expected, dict): + _reject_respelt_keys(expected) + if not isinstance(expected, dict) or "check_fields" not in expected: + if isinstance(expected, dict) and "any_of" in expected: + raise ValueError("any_of is read only with check_fields: true") + return KdaExpectation() + flag = expected["check_fields"] + if not isinstance(flag, bool): + raise ValueError(f"check_fields must be true or false, got {flag!r}") + if not flag: + if "any_of" in expected: + raise ValueError("any_of is read only with check_fields: true") + return KdaExpectation() + if unknown := set(expected) - _ITEM_KEYS: + raise ValueError(f"expected_output has unknown keys {sorted(unknown)}") + base = {key: value for key, value in expected.items() if key in _OPTION_KEYS} + if "any_of" not in expected: + return KdaExpectation(options=(_option(base, "expected_output"),)) + options = expected["any_of"] + if not isinstance(options, list) or len(options) < 2 or not all(isinstance(o, dict) and o for o in options): + raise ValueError(f"any_of must list at least two non-empty objects, got {options!r}") + parsed: list[KdaFieldOption] = [] + for index, option in enumerate(options): + if unknown := set(option) - _OPTION_KEYS: + raise ValueError( + f"any_of[{index}] has keys {sorted(unknown)}; an option may state only {sorted(_OPTION_KEYS)}" + ) + parsed.append(_option({**base, **option}, f"any_of[{index}]")) + return KdaExpectation(options=tuple(parsed)) + + +def _bare_id(using: Any) -> Any: + if isinstance(using, str): + for prefix in _TYPE_PREFIXES: + if using.startswith(prefix): + return using[len(prefix) :] + return using + + +def _filter_key(entry: dict[str, Any]) -> Any: + """A comparable form of one filter: an attribute filter by its id and values, any other as its JSON.""" + state = entry.get("state") + if ( + entry.get("type") == "attribute_filter" + and isinstance(state, dict) + and set(state) <= set(_FILTER_STATES) + and all(isinstance(values, list) and all(isinstance(v, str) for v in values) for values in state.values()) + ): + return ( + "attribute_filter", + _bare_id(entry.get("using")), + tuple(sorted(state.get("include") or [])), + tuple(sorted(state.get("exclude") or [])), + ) + return json.dumps(entry, sort_keys=True, default=str) + + +def _measure_matches(candidate: dict[str, Any], actual: Any) -> bool: + if not isinstance(actual, dict): + return False + if candidate["id"] != actual.get("id") or candidate["type"] != actual.get("type"): + return False + expected_aggregation = candidate.get("aggregation") + if expected_aggregation is None: + return True + return str(expected_aggregation).upper() == str(actual.get("aggregation") or "").upper() + + +def _actual_summary(execute_result: Any) -> dict | None: + if not isinstance(execute_result, dict) or execute_result.get("success") is not True: + return None + data = execute_result.get("data") + summary = data.get("summary") if isinstance(data, dict) else None + return summary if isinstance(summary, dict) else None + + +def _within(actual: float, expected: float, tolerance: float) -> bool: + # In decimal, so 100.01 against 100 is a difference of exactly 0.01, not 0.010000000000005116. + return abs(Decimal(repr(actual)) - Decimal(repr(expected))) <= Decimal(repr(tolerance)) + + +def _summary_matches(option: KdaFieldOption, actual: dict | None) -> bool: + if actual is None: + return False + for key, expected in option.summary.items(): + number = _to_float(actual.get(key)) + if number is None or not _within(number, expected, option.tolerance): + return False + return True + + +def _non_date_filters(filters: Any) -> list[Any]: + entries = filters if isinstance(filters, list) else [] + return [entry for entry in entries if not (isinstance(entry, dict) and entry.get("type") == _DATE_FILTER)] + + +def _actual_filters(create_args: dict) -> Any: + """The non-date filters the agent sent, or the malformed value itself so a failed check shows it.""" + filters = create_args.get("filters", []) + return _non_date_filters(filters) if isinstance(filters, list) else filters + + +def _check_option(option: KdaFieldOption, create_args: dict, summary: dict | None) -> dict[str, bool]: + filters = create_args.get("filters", []) + # Omitted filters are no filters. Anything but a list, null included, is malformed: the tool takes a list. + filters_shaped = isinstance(filters, list) + actual_filters = sorted( + (_filter_key(f) if isinstance(f, dict) else repr(f) for f in _non_date_filters(filters)), + key=repr, + ) + return { + "measure": any(_measure_matches(c, create_args.get("measure")) for c in option.measures), + "date_attribute": str(create_args.get("date_attribute_id") or "").strip() == option.date_attribute, + "analyzed_period": _period_key(create_args.get("analyzed_period") or "") == _period_key(option.analyzed_period), + "reference_period": _period_key(create_args.get("reference_period") or "") + == _period_key(option.reference_period), + "filters": filters_shaped and actual_filters == sorted(option.filters, key=repr), + "summary": _summary_matches(option, summary), + } + + +def _expected_view(option: KdaFieldOption) -> dict[str, Any]: + return { + "measure": list(option.measures) if len(option.measures) > 1 else option.measures[0], + "date_attribute": option.date_attribute, + "analyzed_period": option.analyzed_period, + "reference_period": option.reference_period, + "filters": list(option.filter_entries), + "summary": {**option.summary, "absolute_tolerance": option.tolerance}, + } + + +def check_kda_fields(spec: KdaExpectation, create_args: Any, execute_result: Any) -> KdaFieldResult | None: + """The run's field checks against the option that matched most fields, the first one on a tie. + + None when the item does not opt in or the run never called create: there was nothing to check, and + the completion checks already fail that run. Arguments that are not an object fail every field. + """ + if not spec.check_fields or create_args is None: + return None + summary = _actual_summary(execute_result) + if not isinstance(create_args, dict): + return KdaFieldResult( + checks=dict.fromkeys(KDA_FIELDS, False), + option_index=0, + expected=_expected_view(spec.options[0]), + actual=dict.fromkeys(KDA_FIELDS) | {"summary": summary}, + ) + results = [_check_option(option, create_args, summary) for option in spec.options] + best = max(range(len(results)), key=lambda i: sum(results[i].values())) + actual = { + "measure": create_args.get("measure"), + "date_attribute": create_args.get("date_attribute_id"), + "analyzed_period": create_args.get("analyzed_period"), + "reference_period": create_args.get("reference_period"), + "filters": _actual_filters(create_args), + "summary": summary, + } + return KdaFieldResult( + checks=results[best], + option_index=best, + expected=_expected_view(spec.options[best]), + actual=actual, + ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py index e92464bf9..9dd38caa7 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py @@ -7,11 +7,12 @@ import os import time from dataclasses import dataclass, field +from typing import Any import httpx from gooddata_eval.core.agentic._failed_runs import build_failed_runs -from gooddata_eval.core.agentic._failure_message import failed_checks_from +from gooddata_eval.core.agentic._failure_message import FailedCheck, failed_check_records, failed_checks_from from gooddata_eval.core.agentic._gate import ( DEFAULT_GATE, EvalGate, @@ -19,6 +20,13 @@ log_gate_scores, stamp_gate_metadata, ) +from gooddata_eval.core.agentic._kda_expectation import ( + KDA_FIELD_SCORES, + KdaExpectation, + KdaFieldResult, + check_kda_fields, + parse_kda_expectation, +) from gooddata_eval.core.agentic._outcome import ( agentic_detail, agentic_success, @@ -54,6 +62,16 @@ _log = logging.getLogger(__name__) +__all__ = [ + "KDA_FIELD_SCORES", + "AgenticKdaSummary", + "KdaEvaluation", + "KdaRunResult", + "KdaSkillAssertionError", + "evaluate_agentic_kda_skill", + "run_agentic_kda_skill", +] + _DEFAULT_K = 1 # Disambiguation safety net only (create+execute always run together in the same turn) -- # 3 real questions' worth (metric, period, +1 slack) since a simulated reply is now sent on @@ -61,6 +79,18 @@ _DEFAULT_MAX_ITERATIONS = 4 +def _hint_source(expected_output: dict) -> dict: + """The fields the simulated user answers from: the item's own, or with ``any_of`` its first option. + + One whole option, so the measure, date attribute and periods it names form an answer the + field checks accept. Values mixed from two options might match neither. + """ + options = expected_output.get("any_of") + if isinstance(options, list) and options and isinstance(options[0], dict): + return {**expected_output, **options[0]} + return expected_output + + def _build_period_hint(expected_output: dict) -> str | None: """Build a period hint from whichever of expected_output's Date Attribute/Analyzed Period/Reference Period are present -- a question about only one of them (e.g. "which @@ -74,7 +104,7 @@ def _build_period_hint(expected_output: dict) -> str | None: return None parts = [] if date_attr: - parts.append(date_attr) + parts.append(str(date_attr)) if analyzed and reference_period: parts.append(f"comparing {analyzed} to {reference_period}") elif analyzed: @@ -155,27 +185,60 @@ def _extract_kda_calls(tool_call_events: list[ToolCallEvent]) -> tuple[dict | No tool calls -- not the last create and last execute picked independently. A new create call clears any earlier execute_result -- it belongs to the create it followed, not to this one. + + An execute names the spec it runs by ``kda_ref``, so it is paired with the create that + returned that ref, even when another create came between them. Once the turn's creates + returned refs, an execute naming any other ref, or no string ref, is ignored: its result + belongs to no arguments the run can score. Only a create that carried no result at all + lets the next execute pair without a ref. A create the tool rejected does not replace an + analysis that already ran. Create arguments that are not a JSON object count as empty + arguments; an execute whose arguments or result are not a JSON object is no execution. """ + created: dict[str, dict] = {} create_args: dict | None = None execute_result: dict | None = None + pairs_without_ref = False for tc in tool_call_events: if tc.function_name == "create_key_driver_analysis": - create_args = tc.parsed_arguments() + args = _json_object(tc.parsed_arguments()) or {} + result = _json_object(tc.parsed_result()) + if result is not None and result.get("success") is True and isinstance(result.get("kda_ref"), str): + created[result["kda_ref"]] = args + if result is not None and result.get("success") is False and execute_result is not None: + continue + create_args = args execute_result = None + pairs_without_ref = not tc.result elif tc.function_name == "execute_key_driver_analysis" and tc.result: - execute_result = tc.parsed_result() + execute_args = _json_object(tc.parsed_arguments()) + ref = execute_args.get("kda_ref") if execute_args is not None else None + if created: + if not isinstance(ref, str) or ref not in created: + continue + create_args = created[ref] + elif not pairs_without_ref or execute_args is None: + continue + execute_result = _json_object(tc.parsed_result()) return create_args, execute_result +def _json_object(value: Any) -> dict | None: + """``value`` when the tool call carried a JSON object, else None. A model can send any JSON.""" + return value if isinstance(value, dict) else None + + @dataclass class KdaEvaluation: """Evaluation scores for a single KDA-skill run. - Scope: asserts only that the KDA process runs to completion -- the tool chain - triggers, executes successfully, and the chat turn ends cleanly with a non-empty - response (``turn_completed`` requires both gen-ai's stream-ended signal and a - non-empty ``text_response`` -- a stream that ends cleanly but delivers nothing to the - user isn't a completed turn either). + Every run is checked for completion: the tool chain triggers, executes successfully, and + the chat turn ends cleanly with a non-empty response (``turn_completed`` requires both + gen-ai's stream-ended signal and a non-empty ``text_response`` -- a stream that ends + cleanly but delivers nothing to the user isn't a completed turn either). + + An item with ``check_fields: true`` also gates on ``fields``: the measure, date attribute, + periods, non-date filters and summary of the create call and its execution. ``fields`` is + None when the item does not opt in or the run never called create. """ triggered: bool @@ -183,16 +246,20 @@ class KdaEvaluation: success: bool turn_completed: bool disambiguated: bool = False + fields: KdaFieldResult | None = None @property def strict_checks(self) -> dict[str, bool]: """Every check strict_pass requires, by name.""" - return { + checks = { "triggered": self.triggered, "executed": self.executed, "success": self.success, "turn_completed": self.turn_completed, } + if self.fields is not None: + checks.update({f"{name}_correct": ok for name, ok in self.fields.checks.items()}) + return checks @property def strict_pass(self) -> bool: @@ -241,6 +308,7 @@ def _evaluate_run( execute_result: dict | None, turn_completed: bool, disambiguated: bool = False, + spec: KdaExpectation | None = None, ) -> KdaEvaluation: triggered = create_args is not None executed = execute_result is not None @@ -251,6 +319,7 @@ def _evaluate_run( success=success, turn_completed=turn_completed, disambiguated=disambiguated, + fields=check_kda_fields(spec, create_args, execute_result) if spec is not None else None, ) @@ -281,6 +350,7 @@ def run_agentic_kda_skill( if k < 1: # k=0 or negative would otherwise silently run once, indistinguishable from k=1. raise ValueError(f"k must be >= 1, got {k}") + spec = parse_kda_expectation(expected_output) run_results: list[KdaRunResult] = [] client = ChatClient( host=host, @@ -376,8 +446,9 @@ def _accumulate(result: ChatResult) -> None: # simulated reply. A false positive (agent had already given a final answer) costs # one harmless extra turn; a false negative (missing a genuine clarifying question) # would hard-fail the run, so the asymmetry favors never trying to tell them apart. - measure_candidates = expected_output.get("Measure") if isinstance(expected_output, dict) else None - period_hint = _build_period_hint(expected_output) if isinstance(expected_output, dict) else None + hint_source = _hint_source(expected_output) if isinstance(expected_output, dict) else None + measure_candidates = hint_source.get("Measure") if hint_source is not None else None + period_hint = _build_period_hint(hint_source) if hint_source is not None else None try: current_question = generate_simulated_kda_response(response_text, measure_candidates, period_hint) disambiguated = True @@ -386,7 +457,7 @@ def _accumulate(result: ChatResult) -> None: exit_reason = LoopExit.SIMULATED_USER_FAILED break - ev = _evaluate_run(create_args, execute_result, turn_completed, disambiguated) + ev = _evaluate_run(create_args, execute_result, turn_completed, disambiguated, spec) return KdaRunResult( conversation_id=conv_id, evaluation=ev, @@ -423,12 +494,7 @@ def _accumulate(result: ChatResult) -> None: pass_at_k = any(r.evaluation.strict_pass for r in run_results) pass_power_k = all(r.evaluation.strict_pass for r in run_results) - best = max( - run_results, - key=lambda r: sum( - [r.evaluation.triggered, r.evaluation.executed, r.evaluation.success, r.evaluation.turn_completed] - ), - ) + best = max(run_results, key=lambda r: sum(r.evaluation.strict_checks.values())) return AgenticKdaSummary( run_results=run_results, pass_at_k=pass_at_k, @@ -456,6 +522,7 @@ def _run_detail(run: KdaRunResult) -> dict: "disambiguated": ev.disambiguated, "actual_create_args": run.actual_create_args, "actual_execute_result": run.actual_execute_result, + **_field_detail(ev), # Why the loop stopped -- see LoopExit. Per-run rather than best-only: on a failing # run it is the first thing worth reading. "exit_reason": run.exit_reason.value, @@ -464,9 +531,29 @@ def _run_detail(run: KdaRunResult) -> dict: } +def _field_detail(ev: KdaEvaluation) -> dict: + """The field verdicts as top-level booleans, which the report's quality score counts, plus what they compared.""" + if ev.fields is None: + return {} + return { + **{f"{name}_correct": ok for name, ok in ev.fields.checks.items()}, + "field_option": ev.fields.option_index, + "expected_fields": ev.fields.expected, + } + + def _failed_checks(run: KdaRunResult) -> list[dict]: - """The checks this run failed, by name. What the agent sent is in the run's detail.""" - return failed_checks_from(run.evaluation.strict_checks) + """The checks this run failed, by name, a field check with its expected and actual value.""" + ev = run.evaluation + completion = {name: ok for name, ok in ev.strict_checks.items() if not name.endswith("_correct")} + records = failed_checks_from(completion) + if ev.fields is not None: + records += failed_check_records( + FailedCheck(f"{name}_correct", expected=ev.fields.expected[name], actual=ev.fields.actual[name]) + for name, ok in ev.fields.checks.items() + if not ok + ) + return records def evaluate_agentic_kda_skill( @@ -496,6 +583,8 @@ def evaluate_agentic_kda_skill( AgenticEvalOutcome on success; on failure the same three values are attached to the raised exception as ``.reasoning_steps``/``.conversation_id``/``.response_id``. """ + # Before the trace opens: a malformed item must fail without a request or an empty trace. + parse_kda_expectation(expected_output) identity = RunIdentity( host, token, @@ -538,13 +627,8 @@ def _write_scores(ctx: RunTraceContext) -> None: pt = ctx.trace(run.conversation_id) run_name = ctx.run_name(run_idx) ev = run.evaluation - # Gates strict_pass -- current scope is completion only (see KdaEvaluation docstring). - strict_checks = { - "kda_triggered": ev.triggered, - "kda_executed": ev.executed, - "kda_success": ev.success, - "kda_turn_completed": ev.turn_completed, - } + # Gates strict_pass: completion, plus the kda_*_correct field checks of an item that opts in. + strict_checks = {f"kda_{name}": ok for name, ok in ev.strict_checks.items()} # Not pt.latency: pt can be any trace of the conversation, not necessarily the KDA turn. turn_wall_clock_sec = run.turn_wall_clock_sec _log.info( @@ -604,6 +688,7 @@ def _write_scores(ctx: RunTraceContext) -> None: disambiguated=ev.disambiguated, actual_create_args=best.actual_create_args, actual_execute_result=best.actual_execute_result, + **_field_detail(ev), # Why the loop stopped -- see LoopExit. exit_reason=best.exit_reason.value, turns_used=best.turns_used, @@ -623,7 +708,9 @@ def _write_scores(ctx: RunTraceContext) -> None: message = ( f"KDA skill assertion failed. {gate_note} strict_pass={ev.strict_pass} " f"(triggered={ev.triggered}, executed={ev.executed}, " - f"success={ev.success}, turn_completed={ev.turn_completed}). " + f"success={ev.success}, turn_completed={ev.turn_completed}" + + (f", fields={ev.fields.checks}" if ev.fields is not None else "") + + "). " f"Actual create args: {best.actual_create_args}. " f"Actual execute result: {best.actual_execute_result}." ) diff --git a/packages/gooddata-eval/tests/test_agentic_kda_skill_fields.py b/packages/gooddata-eval/tests/test_agentic_kda_skill_fields.py new file mode 100644 index 000000000..bd76e3887 --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_kda_skill_fields.py @@ -0,0 +1,827 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +# SPDX-License-Identifier: LicenseRef-GoodData-Enterprise +import json +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from gooddata_eval.core.agentic._kda_expectation import ( + KDA_FIELD_SCORES, + check_kda_fields, + parse_kda_expectation, +) +from gooddata_eval.core.agentic.kda_skill import ( + AgenticKdaSummary, + KdaSkillAssertionError, + _extract_kda_calls, + evaluate_agentic_kda_skill, + run_agentic_kda_skill, +) +from gooddata_eval.core.models import AgenticEvalOutcome, ChatResult, ToolCallEvent + +# Shapes trimmed from nightly kda_skill traces on the globalmart fixture. +_REGION = "label/dim_geography_region.region_name" +_EXPECTED = { + "check_fields": True, + "Measure": {"id": "total_sales_amount_daily_store", "type": "metric"}, + "Date Attribute": "transaction_date.quarter", + "Analyzed Period": "2024-4", + "Reference Period": "2024-3", + "Filters": [{"type": "attribute_filter", "state": {"exclude": ["United States East"]}, "using": _REGION}], + "Summary": { + "change": -1273867.76, + "analyzed_value": 13868253.55, + "reference_value": 15142121.31, + "absolute_tolerance": 0.01, + }, +} +_CREATE = { + "measure": {"id": "total_sales_amount_daily_store", "type": "metric", "aggregation": None}, + "date_attribute_id": "transaction_date.quarter", + "analyzed_period": "2024-4", + "reference_period": "2024-3", + "filters": [{"type": "attribute_filter", "using": _REGION, "state": {"exclude": ["United States East"]}}], +} +_EXECUTE = { + "success": True, + "data": { + "summary": { + "reference_value": 15142121.31, + "analyzed_value": 13868253.55, + "change": -1273867.7599999998, + "change_percentage": -8.412743062352336, + } + }, +} +# 2a9704f3: the dashboard chart uses the transaction date, the question reads as the return date. +_BY_TRANSACTION: dict[str, Any] = { + "Date Attribute": "transaction_date.quarter", + "Summary": {"analyzed_value": 184, "reference_value": 163, "change": 21}, +} +_BY_RETURN: dict[str, Any] = { + "Date Attribute": "return_date.quarter", + "Summary": {"analyzed_value": 191, "reference_value": 156, "change": 35}, +} +_ANY_OF = { + "check_fields": True, + "Measure": {"id": "total_quantity_returned_returns", "type": "metric"}, + "Analyzed Period": "2026-2", + "Reference Period": "2025-2", + "Filters": [], + "any_of": [_BY_TRANSACTION, _BY_RETURN], +} + + +def _with(base: dict, **changes: Any) -> dict: + return {**base, **changes} + + +def _summary(analyzed: float, reference: float) -> dict: + return { + "success": True, + "data": {"summary": {"analyzed_value": analyzed, "reference_value": reference, "change": analyzed - reference}}, + } + + +# --------------------------------------------------------------------------- # +# parse_kda_expectation + + +def test_items_without_check_fields_are_not_field_checked() -> None: + assert not parse_kda_expectation({"Measure": {"id": "m", "type": "metric"}}).check_fields + assert not parse_kda_expectation(_with(_EXPECTED, check_fields=False)).check_fields + assert not parse_kda_expectation("not a dict").check_fields + assert check_kda_fields(parse_kda_expectation({}), _CREATE, _EXECUTE) is None + + +def test_check_fields_reads_every_field() -> None: + (option,) = parse_kda_expectation(_EXPECTED).options + assert option.date_attribute == "transaction_date.quarter" + assert option.summary == {"change": -1273867.76, "analyzed_value": 13868253.55, "reference_value": 15142121.31} + assert option.tolerance == 0.01 + + +@pytest.mark.parametrize( + ("expected", "message"), + [ + (_with(_EXPECTED, check_fields="yes"), "check_fields must be true or false"), + ({k: v for k, v in _EXPECTED.items() if k != "Summary"}, "lacks Summary"), + ({k: v for k, v in _EXPECTED.items() if k != "Filters"}, "lacks Filters"), + (_with(_EXPECTED, Sumary={}), "unknown keys"), + (_with(_EXPECTED, Measure={"type": "metric"}), "non-empty string id"), + (_with(_EXPECTED, Measure=[]), "at least one candidate"), + (_with(_EXPECTED, Measure={"id": "m", "type": "metric", "agg": "SUM"}), "unknown keys"), + (_with(_EXPECTED, **{"Analyzed Period": ""}), "Analyzed Period must be a non-empty string"), + (_with(_EXPECTED, **{"Date Attribute": True}), "Date Attribute must be a non-empty string"), + (_with(_EXPECTED, **{"Date Attribute": 2024}), "Date Attribute must be a non-empty string"), + (_with(_EXPECTED, Filters=["region"]), "Filters must hold objects"), + (_with(_EXPECTED, Summary="13868253.55"), "Summary must be an object"), + (_with(_EXPECTED, Summary={"change": True}), "change must be a number"), + (_with(_EXPECTED, Summary={"change": "inf"}), "change must be a number"), + (_with(_EXPECTED, Filters=None), "Filters must be a list"), + ( + _with(_EXPECTED, Filters=[{"type": "date_filter", "using": "dataset/transaction_date"}]), + "must not hold a date_filter", + ), + (_with(_EXPECTED, Summary={"absolute_tolerance": 0.01}), "at least one of"), + (_with(_EXPECTED, Summary={"change": "a lot"}), "change must be a number"), + (_with(_EXPECTED, Summary={"change": 1, "absolute_tolerance": "abc"}), "absolute_tolerance"), + (_with(_EXPECTED, Summary={"change": 1, "absolute_tolerance": -1}), "absolute_tolerance"), + (_with(_EXPECTED, Summary={"change": 1, "change_pct": 3}), "unknown keys"), + ({k: v for k, v in _ANY_OF.items() if k != "check_fields"}, "any_of is read only with check_fields"), + (_with(_ANY_OF, check_fields=False), "any_of is read only with check_fields"), + (_with(_ANY_OF, any_of=[_BY_TRANSACTION]), "at least two"), + (_with(_ANY_OF, any_of=[_BY_TRANSACTION, {}]), "at least two"), + (_with(_ANY_OF, any_of=[_BY_TRANSACTION, {"check_fields": True}]), "may state only"), + (_with(_ANY_OF, any_of=[_BY_TRANSACTION, {"Summary": {"change": 1}}]), "any_of[1] lacks Date Attribute"), + (_with(_EXPECTED, Measure={"id": "m", "type": "Metric"}), "type must be one of"), + (_with(_EXPECTED, Measure={"id": "m", "type": "facts"}), "type must be one of"), + (_with(_EXPECTED, Measure={"id": "m", "type": "fact", "aggregation": "TOTAL"}), "aggregation must be one of"), + (_with(_EXPECTED, Filters=[{"type": "attribute_filter", "state": {"include": ["A"]}}]), "non-empty using"), + ( + _with(_EXPECTED, Filters=[{"type": "attribute_filter", "using": _REGION, "state": {"exclude": "East"}}]), + "non-empty list of strings", + ), + ( + _with(_EXPECTED, Filters=[{"type": "attribute_filter", "using": _REGION, "state": {"include": []}}]), + "non-empty list of strings", + ), + ( + _with(_EXPECTED, Filters=[{"type": "attribute_filter", "using": _REGION, "state": {"include": [None]}}]), + "non-empty list of strings", + ), + ( + _with( + _EXPECTED, + Filters=[{"type": "attribute_filter", "using": _REGION, "state": {"include": ["A"], "exclude": ["B"]}}], + ), + "exactly one of include, exclude", + ), + ], +) +def test_malformed_field_checks_are_rejected(expected: dict, message: str) -> None: + with pytest.raises(ValueError, match=message.replace("[", r"\[").replace("]", r"\]")): + parse_kda_expectation(expected) + + +@pytest.mark.parametrize( + ("respelt", "canonical"), + [("check fields", "check_fields"), ("Check_Fields", "check_fields"), ("any of", "any_of"), ("any-of", "any_of")], +) +def test_a_respelt_opt_in_key_is_rejected_not_ignored(respelt: str, canonical: str) -> None: + expected = {k: v for k, v in _EXPECTED.items() if k != "check_fields"} | {respelt: True} + with pytest.raises(ValueError, match=f"write '{canonical}', not '{respelt}'"): + parse_kda_expectation(expected) + + +def test_aggregation_is_read_in_any_case() -> None: + (option,) = parse_kda_expectation( + _with(_EXPECTED, Measure={"id": "sales_amount", "type": "fact", "aggregation": "sum"}) + ).options + assert option.measures[0]["aggregation"] == "sum" + + +def test_tolerance_given_as_a_string_is_read_as_a_number() -> None: + (option,) = parse_kda_expectation(_with(_EXPECTED, Summary={"change": 1, "absolute_tolerance": "1E-2"})).options + assert option.tolerance == 0.01 + + +def test_tolerance_defaults_to_a_cent() -> None: + (option,) = parse_kda_expectation(_with(_EXPECTED, Summary={"change": 1})).options + assert option.tolerance == 0.01 + + +def test_field_scores_are_named_after_the_fields() -> None: + assert KDA_FIELD_SCORES == ( + "kda_measure_correct", + "kda_date_attribute_correct", + "kda_analyzed_period_correct", + "kda_reference_period_correct", + "kda_filters_correct", + "kda_summary_correct", + ) + + +# --------------------------------------------------------------------------- # +# check_kda_fields + + +def test_a_matching_run_passes_every_field() -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _CREATE, _EXECUTE) + assert result is not None + assert result.passed + assert result.option_index == 0 + + +def test_no_create_call_means_nothing_to_check() -> None: + assert check_kda_fields(parse_kda_expectation(_EXPECTED), None, None) is None + + +def test_a_date_filter_the_agent_adds_is_ignored() -> None: + create = _with( + _CREATE, + filters=[ + *_CREATE["filters"], + {"type": "date_filter", "using": "dataset/transaction_date", "from": "2024-07-01", "to": "2024-12-31"}, + ], + ) + result = check_kda_fields(parse_kda_expectation(_EXPECTED), create, _EXECUTE) + assert result is not None + assert result.passed + assert result.actual["filters"] == _CREATE["filters"] + + +def test_a_date_filter_that_changes_the_numbers_fails_summary() -> None: + """ce857c85: the agent's own week bounds cut a day out of the reference week.""" + expected = _with( + _EXPECTED, + **{"Date Attribute": "return_date.week", "Analyzed Period": "2026-21", "Reference Period": "2026-20"}, + Filters=[], + Summary={"analyzed_value": 1263.4, "reference_value": 2140.89}, + ) + create = _with( + _CREATE, + date_attribute_id="return_date.week", + analyzed_period="2026-21", + reference_period="2026-20", + filters=[{"type": "date_filter", "using": "dataset/return_date", "from": "2026-05-11", "to": "2026-05-24"}], + ) + result = check_kda_fields(parse_kda_expectation(expected), create, _summary(1263.4, 1972.36)) + assert result is not None + assert result.checks == { + "measure": True, + "date_attribute": True, + "analyzed_period": True, + "reference_period": True, + "filters": True, + "summary": False, + } + + +def test_an_extra_non_date_filter_fails_filters() -> None: + """555dcae3: region South plus country United States instead of region United States South.""" + create = _with( + _CREATE, + filters=[ + {"type": "attribute_filter", "using": _REGION, "state": {"include": ["South"]}}, + {"type": "attribute_filter", "using": "label/sql_store_country.country_name", "state": {"include": ["US"]}}, + ], + ) + result = check_kda_fields(parse_kda_expectation(_EXPECTED), create, _EXECUTE) + assert result is not None + assert result.checks["filters"] is False + + +@pytest.mark.parametrize("filters", [{"type": "attribute_filter"}, "none", 0, None]) +def test_filters_that_are_not_a_list_fail_filters_and_are_reported(filters: object) -> None: + spec = parse_kda_expectation(_with(_EXPECTED, Filters=[])) + result = check_kda_fields(spec, _with(_CREATE, filters=filters), _EXECUTE) + assert result is not None + assert result.checks["filters"] is False + assert result.actual["filters"] == filters + + +def test_omitted_filters_are_no_filters() -> None: + spec = parse_kda_expectation(_with(_EXPECTED, Filters=[])) + create = {k: v for k, v in _CREATE.items() if k != "filters"} + result = check_kda_fields(spec, create, _EXECUTE) + assert result is not None + assert result.checks["filters"] is True + + +def test_a_missing_filter_fails_filters() -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _with(_CREATE, filters=[]), _EXECUTE) + assert result is not None + assert result.checks["filters"] is False + + +def test_include_and_exclude_are_different_filters() -> None: + flipped = [{"type": "attribute_filter", "using": _REGION, "state": {"include": ["United States East"]}}] + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _with(_CREATE, filters=flipped), _EXECUTE) + assert result is not None + assert result.checks["filters"] is False + + +def test_a_filter_by_attribute_id_matches_one_by_label_id() -> None: + by_attribute = [ + { + "type": "attribute_filter", + "using": "attribute/dim_geography_region.region_name", + "state": {"exclude": ["United States East"]}, + } + ] + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _with(_CREATE, filters=by_attribute), _EXECUTE) + assert result is not None + assert result.checks["filters"] is True + + +def test_filter_values_match_in_any_order() -> None: + expected = _with( + _EXPECTED, + Filters=[{"type": "attribute_filter", "using": _REGION, "state": {"include": ["A", "B"]}}], + ) + create = _with(_CREATE, filters=[{"type": "attribute_filter", "using": _REGION, "state": {"include": ["B", "A"]}}]) + result = check_kda_fields(parse_kda_expectation(expected), create, _EXECUTE) + assert result is not None + assert result.checks["filters"] is True + + +def test_a_ranking_filter_matches_on_its_content_not_its_key_order() -> None: + ranking = {"type": "ranking_filter", "using": "metric/net_sales", "top": 5} + spec = parse_kda_expectation(_with(_EXPECTED, Filters=[ranking])) + reordered = {"top": 5, "using": "metric/net_sales", "type": "ranking_filter"} + same = check_kda_fields(spec, _with(_CREATE, filters=[reordered]), _EXECUTE) + other = check_kda_fields(spec, _with(_CREATE, filters=[{**ranking, "top": 3}]), _EXECUTE) + assert same is not None + assert same.checks["filters"] is True + assert other is not None + assert other.checks["filters"] is False + + +@pytest.mark.parametrize( + "malformed", + [ + {"type": "attribute_filter", "state": {"exclude": ["United States East"]}}, + {"type": "attribute_filter", "using": 7, "state": {"exclude": ["United States East"]}}, + {"type": "attribute_filter", "using": _REGION, "state": {"exclude": "United States East"}}, + "label/dim_geography_region.region_name", + ], +) +def test_a_malformed_filter_from_the_agent_fails_filters_without_an_error(malformed: object) -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _with(_CREATE, filters=[malformed]), _EXECUTE) + assert result is not None + assert result.checks["filters"] is False + + +def test_another_measure_fails_measure() -> None: + """ba0a7d21: the gift-card count picked from the dashboard's year chart.""" + create = _with(_CREATE, measure={"id": "gift_card_transaction_total_count", "type": "metric", "aggregation": None}) + result = check_kda_fields(parse_kda_expectation(_EXPECTED), create, _EXECUTE) + assert result is not None + assert result.checks["measure"] is False + + +def test_measure_matches_any_listed_candidate() -> None: + expected = _with( + _EXPECTED, + Measure=[{"id": "other", "type": "metric"}, {"id": "total_sales_amount_daily_store", "type": "metric"}], + ) + result = check_kda_fields(parse_kda_expectation(expected), _CREATE, _EXECUTE) + assert result is not None + assert result.checks["measure"] is True + + +def test_measure_type_must_match() -> None: + create = _with(_CREATE, measure={"id": "total_sales_amount_daily_store", "type": "fact", "aggregation": "SUM"}) + result = check_kda_fields(parse_kda_expectation(_EXPECTED), create, _EXECUTE) + assert result is not None + assert result.checks["measure"] is False + + +def test_fact_aggregation_is_checked_only_when_expected() -> None: + fact = {"id": "sales_amount", "type": "fact"} + create = _with(_CREATE, measure={**fact, "aggregation": "sum"}) + spec_any = parse_kda_expectation(_with(_EXPECTED, Measure=fact)) + spec_sum = parse_kda_expectation(_with(_EXPECTED, Measure={**fact, "aggregation": "SUM"})) + spec_avg = parse_kda_expectation(_with(_EXPECTED, Measure={**fact, "aggregation": "AVG"})) + verdicts = [check_kda_fields(spec, create, _EXECUTE) for spec in (spec_any, spec_sum, spec_avg)] + assert [v.checks["measure"] if v else None for v in verdicts] == [True, True, False] + + +def test_another_date_granularity_fails_date_attribute() -> None: + """2af7ae17: months instead of quarters.""" + result = check_kda_fields( + parse_kda_expectation(_EXPECTED), _with(_CREATE, date_attribute_id="transaction_date.month"), _EXECUTE + ) + assert result is not None + assert result.checks["date_attribute"] is False + + +def test_periods_are_compared_as_text() -> None: + expected = _with(_EXPECTED, **{"Analyzed Period": 2024, "Reference Period": "2023"}) + create = _with(_CREATE, analyzed_period="2024", reference_period=2023) + result = check_kda_fields(parse_kda_expectation(expected), create, _EXECUTE) + assert result is not None + assert result.checks["analyzed_period"] is True + assert result.checks["reference_period"] is True + + +@pytest.mark.parametrize( + ("expected", "actual", "same"), + [ + ("2024-01", "2024-1", True), + ("2026-03", "2026-3", True), + ("2026-07-15", "2026-7-15", True), + ("2024-3", "2024-Q3", False), + ("2024-3", "2024-4", False), + ], +) +def test_periods_match_on_their_numbers(expected: str, actual: str, same: bool) -> None: + spec = parse_kda_expectation(_with(_EXPECTED, **{"Analyzed Period": expected})) + result = check_kda_fields(spec, _with(_CREATE, analyzed_period=actual), _EXECUTE) + assert result is not None + assert result.checks["analyzed_period"] is same + + +def test_arguments_that_are_not_an_object_fail_every_field() -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), ["x"], _EXECUTE) + assert result is not None + assert not any(result.checks.values()) + + +def test_swapped_periods_fail_both() -> None: + create = _with(_CREATE, analyzed_period="2024-3", reference_period="2024-4") + result = check_kda_fields(parse_kda_expectation(_EXPECTED), create, _EXECUTE) + assert result is not None + assert result.checks["analyzed_period"] is False + assert result.checks["reference_period"] is False + + +def test_summary_outside_the_tolerance_fails() -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _CREATE, _summary(13868253.55, 15142121.33)) + assert result is not None + assert result.checks["summary"] is False + + +@pytest.mark.parametrize( + ("expected", "actual", "within"), + [ + (100, 100.01, True), + (100, 99.99, True), + (100, 100.0101, False), + (15142121.31, 15142121.32, True), + (15142121.31, 15142121.33, False), + (-1273867.76, -1273867.7599999998, True), + ], +) +def test_the_tolerance_bound_is_inclusive(expected: float, actual: float, within: bool) -> None: + spec = parse_kda_expectation(_with(_EXPECTED, Summary={"analyzed_value": expected})) + result = check_kda_fields(spec, _CREATE, {"success": True, "data": {"summary": {"analyzed_value": actual}}}) + assert result is not None + assert result.checks["summary"] is within + + +def test_summary_checks_only_the_values_the_item_states() -> None: + expected = _with(_EXPECTED, Summary={"analyzed_value": 13868253.55}) + result = check_kda_fields(parse_kda_expectation(expected), _CREATE, _summary(13868253.55, 0)) + assert result is not None + assert result.checks["summary"] is True + + +@pytest.mark.parametrize( + "execute_result", + [ + None, + {"success": False, "data": {"summary": _EXECUTE["data"]["summary"]}}, + {"success": True, "data": {}}, + {"success": True, "data": {"summary": {"analyzed_value": "n/a"}}}, + ], +) +def test_summary_fails_without_a_usable_summary(execute_result: dict | None) -> None: + result = check_kda_fields(parse_kda_expectation(_EXPECTED), _CREATE, execute_result) + assert result is not None + assert result.checks["summary"] is False + assert result.checks["measure"] is True + + +def test_any_of_passes_on_either_option_and_names_it() -> None: + spec = parse_kda_expectation(_ANY_OF) + create = { + "measure": {"id": "total_quantity_returned_returns", "type": "metric", "aggregation": None}, + "date_attribute_id": "return_date.quarter", + "analyzed_period": "2026-2", + "reference_period": "2025-2", + "filters": [], + } + by_return = check_kda_fields(spec, create, _summary(191, 156)) + by_transaction = check_kda_fields( + spec, _with(create, date_attribute_id="transaction_date.quarter"), _summary(184, 163) + ) + assert by_return is not None + assert by_return.passed + assert by_return.option_index == 1 + assert by_transaction is not None + assert by_transaction.passed + assert by_transaction.option_index == 0 + + +def test_the_simulated_user_answers_from_one_whole_any_of_option() -> None: + """The base measure is replaced in every option, so offering it would steer the agent to a failing answer.""" + expected = _with( + _ANY_OF, + Measure={"id": "base_measure", "type": "metric"}, + any_of=[ + {**_BY_TRANSACTION, "Measure": {"id": "first", "type": "metric"}}, + {**_BY_RETURN, "Measure": {"id": "second", "type": "metric"}}, + ], + ) + client = MagicMock() + client.create_conversation.return_value = "conv-1" + client.send_message.side_effect = [ + ChatResult.model_validate( + {"textResponse": "Which date: transaction or return?", "toolCallEvents": [], "stream_ended": True} + ), + _chat_result(_CREATE, _EXECUTE), + ] + with ( + patch("gooddata_eval.core.agentic.kda_skill.ChatClient", return_value=client), + patch( + "gooddata_eval.core.agentic.kda_skill.generate_simulated_kda_response", return_value="Transaction date." + ) as simulate, + ): + run_agentic_kda_skill( + host="http://host", token="tok", workspace_id="ws1", question="q", expected_output=expected + ) + _, measure_candidates, period_hint = simulate.call_args.args + assert measure_candidates == {"id": "first", "type": "metric"} + assert period_hint == "transaction_date.quarter, comparing 2026-2 to 2025-2" + + +def test_any_of_does_not_mix_one_options_date_with_anothers_summary() -> None: + spec = parse_kda_expectation(_ANY_OF) + create = { + "measure": {"id": "total_quantity_returned_returns", "type": "metric"}, + "date_attribute_id": "return_date.quarter", + "analyzed_period": "2026-2", + "reference_period": "2025-2", + "filters": [], + } + result = check_kda_fields(spec, create, _summary(184, 163)) + assert result is not None + assert not result.passed + assert result.option_index == 0 # a tie on five fields goes to the first option + assert result.expected["date_attribute"] == "transaction_date.quarter" + + +# --------------------------------------------------------------------------- # +# run_agentic_kda_skill / evaluate_agentic_kda_skill + + +def _chat_result(create: dict, execute: dict) -> ChatResult: + return ChatResult.model_validate( + { + "textResponse": "Here is the analysis.", + "toolCallEvents": [ + { + "functionName": "create_key_driver_analysis", + "functionArguments": json.dumps(create), + "result": None, + }, + { + "functionName": "execute_key_driver_analysis", + "functionArguments": "{}", + "result": json.dumps(execute), + }, + ], + "reasoningStepCount": 1, + "reasoningSteps": [], + "stream_ended": True, + } + ) + + +def _client(create: dict = _CREATE, execute: dict = _EXECUTE) -> MagicMock: + client = MagicMock() + client.create_conversation.return_value = "conv-1" + client.send_message.return_value = _chat_result(create, execute) + return client + + +def _run(client: MagicMock, expected: dict) -> AgenticKdaSummary: + with patch("gooddata_eval.core.agentic.kda_skill.ChatClient", return_value=client): + return run_agentic_kda_skill( + host="http://host", token="tok", workspace_id="ws1", question="q", expected_output=expected + ) + + +def test_a_run_matching_every_field_passes() -> None: + ev = _run(_client(), _EXPECTED).best.evaluation + assert ev.strict_pass + assert ev.strict_checks["summary_correct"] is True + + +def test_a_wrong_field_fails_the_run() -> None: + summary = _run(_client(create=_with(_CREATE, analyzed_period="2023-4")), _EXPECTED) + ev = summary.best.evaluation + assert not ev.strict_pass + assert not summary.pass_at_k + assert ev.strict_checks["analyzed_period_correct"] is False + assert ev.success + + +def test_completion_only_items_ignore_wrong_fields() -> None: + expected = {k: v for k, v in _EXPECTED.items() if k != "check_fields"} + ev = _run(_client(create=_with(_CREATE, analyzed_period="2023-4")), expected).best.evaluation + assert ev.strict_pass + assert ev.fields is None + assert set(ev.strict_checks) == {"triggered", "executed", "success", "turn_completed"} + + +def test_a_malformed_item_fails_before_any_request() -> None: + client = _client() + with pytest.raises(ValueError, match="lacks Summary"): + _run(client, {k: v for k, v in _EXPECTED.items() if k != "Summary"}) + client.create_conversation.assert_not_called() + client.send_message.assert_not_called() + + +def _evaluate(client: MagicMock, expected: dict, capture: dict | None = None) -> AgenticEvalOutcome: + def _capture(_submit: object, _identity: object, **kwargs: Any) -> None: + if capture is not None: + capture["write_scores"] = kwargs["write_scores"] + + with ( + patch("gooddata_eval.core.agentic.kda_skill.ChatClient", return_value=client), + patch("gooddata_eval.core.agentic.kda_skill.submit_trace_scoring", _capture), + ): + return evaluate_agentic_kda_skill( + host="http://host/api/v1/actions/workspaces/ws1/ai", + token="tok", + workspace_id="ws1", + question="q", + expected_output=expected, + k=1, + max_iterations=1, + langfuse=MagicMock(), + dataset_item_id="item-1", + ) + + +def _scores(capture: dict) -> dict: + ctx = MagicMock() + capture["write_scores"](ctx) + return {c.kwargs["name"]: c.kwargs["value"] for c in ctx.score.call_args_list} + + +def test_field_scores_reach_langfuse() -> None: + capture: dict = {} + _evaluate(_client(), _EXPECTED, capture) + scores = _scores(capture) + assert {name: scores[name] for name in KDA_FIELD_SCORES} == dict.fromkeys(KDA_FIELD_SCORES, 1.0) + assert scores["kda_triggered"] == 1.0 + + +def test_completion_only_items_publish_no_field_scores() -> None: + capture: dict = {} + _evaluate(_client(), {k: v for k, v in _EXPECTED.items() if k != "check_fields"}, capture) + assert not set(KDA_FIELD_SCORES) & set(_scores(capture)) + + +def test_a_failing_field_is_reported_with_expected_and_actual() -> None: + capture: dict = {} + client = _client(create=_with(_CREATE, date_attribute_id="transaction_date.month")) + with pytest.raises(KdaSkillAssertionError) as exc_info: + _evaluate(client, _EXPECTED, capture) + assert _scores(capture)["kda_date_attribute_correct"] == 0.0 + err = exc_info.value + assert "date_attribute" in str(err) + (failed_run,) = err.failed_runs + assert { + "name": "date_attribute_correct", + "expected": "transaction_date.quarter", + "actual": "transaction_date.month", + } in failed_run["failed_checks"] + assert err.detail["date_attribute_correct"] is False + assert err.detail["field_option"] == 0 + + +def test_a_malformed_item_fails_before_the_trace_opens() -> None: + with ( + patch("gooddata_eval.core.agentic.kda_skill.open_item_trace") as mock_open, + pytest.raises(ValueError, match="check_fields must be true or false"), + ): + evaluate_agentic_kda_skill( + host="http://host", + token="tok", + workspace_id="ws1", + question="q", + expected_output=_with(_EXPECTED, check_fields="true"), + ) + mock_open.assert_not_called() + + +def _event(name: str, arguments: object, result: object = None) -> ToolCallEvent: + return ToolCallEvent.model_validate( + { + "functionName": name, + "functionArguments": json.dumps(arguments), + "result": None if result is None else json.dumps(result), + } + ) + + +def test_execute_is_paired_with_the_create_whose_ref_it_names() -> None: + first = _with(_CREATE, analyzed_period="2024-4") + second = _with(_CREATE, analyzed_period="2023-4") + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", first, {"success": True, "kda_ref": "kda_1"}), + _event("create_key_driver_analysis", second, {"success": True, "kda_ref": "kda_2"}), + _event("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + ] + ) + assert create_args == first + assert execute_result == _EXECUTE + + +def test_an_execute_naming_an_unknown_ref_is_not_paired_with_another_create() -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"}), + _event("execute_key_driver_analysis", {"kda_ref": "kda_9"}, _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result is None + + +@pytest.mark.parametrize("ref", [[], {}, None, 1]) +def test_an_execute_with_a_malformed_ref_is_skipped_without_an_error(ref: object) -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"}), + _event("execute_key_driver_analysis", {"kda_ref": ref}, _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result is None + + +def test_a_create_with_a_malformed_result_does_not_pair_without_a_ref() -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE, []), + _event("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result is None + + +def test_an_execute_with_malformed_arguments_is_no_execution() -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE), + _event("execute_key_driver_analysis", "kda_1", _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result is None + + +def test_without_refs_an_execute_belongs_to_the_create_before_it() -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE), + _event("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result == _EXECUTE + + +def test_a_rejected_create_after_the_analysis_ran_is_ignored() -> None: + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"}), + _event("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + _event("create_key_driver_analysis", {"measure": {}}, {"success": False, "error": "bad date"}), + ] + ) + assert create_args == _CREATE + assert execute_result == _EXECUTE + + +def test_a_rejected_create_then_a_retry_scores_the_retry() -> None: + """0d6d3f7f: a snapshot date the measure cannot use, then the transaction date.""" + rejected = _with(_CREATE, date_attribute_id="snapshot_date.day") + create_args, execute_result = _extract_kda_calls( + [ + _event("create_key_driver_analysis", rejected, {"success": False, "error": "not valid for the measure"}), + _event("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"}), + _event("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + ] + ) + assert create_args == _CREATE + assert execute_result == _EXECUTE + + +def test_tool_calls_that_are_not_objects_do_not_break_the_run() -> None: + client = MagicMock() + client.create_conversation.return_value = "conv-1" + client.send_message.return_value = ChatResult.model_validate( + { + "textResponse": "Done.", + "toolCallEvents": [ + {"functionName": "create_key_driver_analysis", "functionArguments": '["x"]', "result": None}, + {"functionName": "execute_key_driver_analysis", "functionArguments": '"kda_1"', "result": "[1]"}, + ], + "reasoningStepCount": 1, + "reasoningSteps": [], + "stream_ended": True, + } + ) + ev = _run(client, _EXPECTED).best.evaluation + assert ev.triggered + assert not ev.executed + assert not ev.strict_pass