From 54725d6c34d9600a7390efafde57ae99b98b025a Mon Sep 17 00:00:00 2001 From: duongthimy Date: Wed, 25 Nov 2026 11:01:35 +0100 Subject: [PATCH] feat(gooddata-eval): check how a search item shows found objects Four opt-in keys for agentic_search items: - expect_user_requested_search: a search_objects call asked for the Search list (or none did) - widget_objects: each type/id is in a searchResults part, not only in a search_objects result - forbidden_parts: no part of these types (document, report, dashboard drafts) is streamed - no_object_urls: the text links to no workspace object Each check is published as its own score; items without the keys are scored as before. jira: QA-30344 risk: low --- .../core/agentic/_search_expectation.py | 88 +++++++++ .../gooddata_eval/core/agentic/search_tool.py | 4 + .../tests/test_agentic_search_tool_checks.py | 179 +++++++++++++++++- 3 files changed, 269 insertions(+), 2 deletions(-) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_search_expectation.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_search_expectation.py index e716abc48..4d57440b5 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_search_expectation.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_search_expectation.py @@ -30,6 +30,10 @@ "no_raw_ids", "setup_turns", "report_only", + "expect_user_requested_search", + "widget_objects", + "forbidden_parts", + "no_object_urls", } ) _KNOWN_KEYS = SEARCH_OPTION_KEYS | {"tool_call"} @@ -69,6 +73,25 @@ # a dot or a digit, as the workspace ids have, counts. A one-word id such as metric/revenue is not caught. _ID_MARK = re.compile(r"[_.0-9]") +# The part types gen-ai streams that land in ``ChatResult.unhandled_parts``. A draft the agent builds +# (document, report, dashboard) is one of them; ``forbidden_parts`` may only name these, so a misspelt +# type cannot read as a pass. +_UNHANDLED_PART_TYPES = frozenset( + {"document", "report", "dashboard", "dashboardPatch", "kda", "whatIf", "clarifyingQuestions"} +) +# A link to a workspace object: an absolute URL, or a markdown link to an app path. The UI opens an object +# from the Search list, so an object URL in the text is one the model wrote itself. +_LINK = re.compile(r"https?://[^\s<>()\[\]\"'`]+|\]\(\s*]+)") +# The routes that open an object: an app route (``/workspace//reports/document/``, +# ``/dashboards/#/workspace//dashboard/``), the entity API and Analytical Designer +# (``/analyze/#//``). A help page with a ``workspaces`` segment is none of them. +_OBJECT_PATH = re.compile( + r"/workspace/[^/\s#?]+/(?:reports?|dashboards?|documents?|visualizations?|metrics?|analyze)\b" + r"|/entities/workspaces/[^/\s]+/" + r"|/analyze/#/[^/\s]+/", + re.IGNORECASE, +) + @dataclass(frozen=True) class SearchExpectation: @@ -89,6 +112,10 @@ class SearchExpectation: no_raw_ids: bool = False setup_turns: tuple[str, ...] = () report_only: bool = False + expect_user_requested_search: bool | None = None + widget_objects: tuple[str, ...] = () + forbidden_parts: tuple[str, ...] = () + no_object_urls: bool = False @property def has_turn_checks(self) -> bool: @@ -101,6 +128,10 @@ def has_turn_checks(self) -> bool: or self.answer_rubric or self.expected_limit is not None or self.no_raw_ids + or self.expect_user_requested_search is not None + or self.widget_objects + or self.forbidden_parts + or self.no_object_urls ) @property @@ -184,6 +215,15 @@ def parse_expectation(expected_output: Any) -> SearchExpectation: both = sorted(set(required) & set(forbidden)) if both: raise ValueError(f"tools {both} are both required and forbidden") + widget_objects: tuple[str, ...] = () + if "widget_objects" in raw: + widget_objects = _string_list("widget_objects", raw["widget_objects"]) + for ref in widget_objects: + _object_ref(ref) + forbidden_parts = _string_list("forbidden_parts", raw["forbidden_parts"]) if "forbidden_parts" in raw else () + unknown_parts = sorted(set(forbidden_parts) - _UNHANDLED_PART_TYPES) + if unknown_parts: + raise ValueError(f"forbidden_parts {unknown_parts} are not among {sorted(_UNHANDLED_PART_TYPES)}") limit = raw.get("expected_limit") if "expected_limit" in raw and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 1): raise ValueError(f"expected_limit must be a positive integer, got {limit!r}") @@ -200,6 +240,14 @@ def parse_expectation(expected_output: Any) -> SearchExpectation: no_raw_ids=_flag("no_raw_ids", raw["no_raw_ids"]) if "no_raw_ids" in raw else False, setup_turns=_string_list("setup_turns", raw["setup_turns"]) if "setup_turns" in raw else (), report_only=_flag("report_only", raw["report_only"]) if "report_only" in raw else False, + expect_user_requested_search=( + _flag("expect_user_requested_search", raw["expect_user_requested_search"]) + if "expect_user_requested_search" in raw + else None + ), + widget_objects=widget_objects, + forbidden_parts=forbidden_parts, + no_object_urls=_flag("no_object_urls", raw["no_object_urls"]) if "no_object_urls" in raw else False, ) if "tool_call" not in raw and not spec.has_checks: raise ValueError("expected_output asserts nothing: give tool_call or at least one check") @@ -274,6 +322,27 @@ def raw_ids(text: str) -> list[str]: return _UUID.findall(outside) + typed +def widget_refs(result: ChatResult) -> list[str]: + """Every object the turn's ``searchResults`` parts list, as ``type/id``, first sighting first.""" + refs: dict[tuple[str, str], str] = {} + for part in result.search_results: + for obj in _objects(part): + object_type, object_id = obj.get("type"), obj.get("id") + if isinstance(object_type, str) and isinstance(object_id, str) and object_type and object_id: + refs.setdefault(_ref_key(object_type, object_id), f"{object_type}/{object_id}") + return list(refs.values()) + + +def object_urls(text: str) -> list[str]: + """The links in ``text`` that point at a workspace object: absolute URLs and markdown links to app paths.""" + found: list[str] = [] + for match in _LINK.finditer(text): + link = match.group(1) or match.group(0) + if _OBJECT_PATH.search(link): + found.append(link) + return found + + def deterministic_checks(spec: SearchExpectation, result: ChatResult) -> tuple[dict[str, bool], dict[str, Any]]: """The checks of one scored turn that need no judge, with the evidence of each failure.""" checks: dict[str, bool] = {} @@ -307,4 +376,23 @@ def _check(name: str, ok: bool, why: Any) -> None: if spec.no_raw_ids: found = raw_ids(result.text_response or "") _check("search_no_raw_ids", not found, {"raw_ids": found}) + if spec.expect_user_requested_search is not None: + flags = [call_args(tc).get("user_requested_search") for tc in search_calls(events)] + asked = any(flag is True for flag in flags) + _check( + "search_user_requested", + asked == spec.expect_user_requested_search, + {"expected": spec.expect_user_requested_search, "user_requested_search": flags}, + ) + if spec.widget_objects: + listed = widget_refs(result) + missing = missing_objects(spec.widget_objects, listed) + _check("search_widget_objects", not missing, {"missing": missing, "listed": listed[:30]}) + if spec.forbidden_parts: + streamed = [part.get("type") for part in result.unhandled_parts] + forbidden = [ptype for ptype in streamed if ptype in spec.forbidden_parts] + _check("search_forbidden_parts", not forbidden, {"forbidden": forbidden, "parts": streamed}) + if spec.no_object_urls: + urls = object_urls(result.text_response or "") + _check("search_no_object_urls", not urls, {"object_urls": urls}) return checks, details diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/search_tool.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/search_tool.py index dc0e05e92..e7ba6636c 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/search_tool.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/search_tool.py @@ -91,6 +91,10 @@ def _judge_provider_errors() -> tuple[type[BaseException], ...]: "search_answer", "search_limit", "search_no_raw_ids", + "search_user_requested", + "search_widget_objects", + "search_forbidden_parts", + "search_no_object_urls", ) # The names a score takes where it does not gate the item: every check of a report_only item, and tool_selection of # an item with search_required false. A score name then means the same on every item. diff --git a/packages/gooddata-eval/tests/test_agentic_search_tool_checks.py b/packages/gooddata-eval/tests/test_agentic_search_tool_checks.py index cc29a92c1..29a539006 100644 --- a/packages/gooddata-eval/tests/test_agentic_search_tool_checks.py +++ b/packages/gooddata-eval/tests/test_agentic_search_tool_checks.py @@ -17,9 +17,11 @@ SEARCH_OPTION_KEYS, SearchExpectation, deterministic_checks, + object_urls, parse_expectation, raw_ids, returned_refs, + widget_refs, ) from gooddata_eval.core.agentic.search_tool import ( SEARCH_CONDITIONAL_SCORES, @@ -59,9 +61,16 @@ def _turn( text: str = "Found 2 results.", calls: list[dict] | None = None, widgets: list[dict] | None = None, + parts: list[dict] | None = None, ) -> ChatResult: return ChatResult.model_validate( - {"textResponse": text, "toolCallEvents": calls or [], "searchResults": widgets or [], "responseId": "resp"} + { + "textResponse": text, + "toolCallEvents": calls or [], + "searchResults": widgets or [], + "unhandledParts": parts or [], + "responseId": "resp", + } ) @@ -335,6 +344,162 @@ def test_widget(expect: bool, widgets: int, ok: bool): assert deterministic_checks(parse_expectation({"expect_widget": expect}), result)[0] == {"search_widget": ok} +_DOC_ID = "9a3c8e7e-2f0b-4c55-a1f1-6b0f6a4f1d20" +_DOC_SEARCH = _search_call( + {"keywords": ["Weekly Sales Brief"], "object_types": ["document"], "limit": 10, "user_requested_search": True}, + [_obj("document", _DOC_ID)], +) +_DOC_LOOKUP = _search_call( + {"keywords": ["Weekly Sales Brief"], "object_types": ["document"], "limit": 10, "user_requested_search": False}, + [_obj("document", _DOC_ID)], +) + + +@pytest.mark.parametrize( + ("calls", "expect", "ok"), + [ + ([_DOC_SEARCH], True, True), + ([_DOC_LOOKUP], True, False), + ([_DOC_LOOKUP, _DOC_SEARCH], True, True), + ([], True, False), + ([_DOC_LOOKUP], False, True), + ([_DOC_SEARCH], False, False), + ], +) +def test_user_requested_search_reads_every_search_call(calls: list[dict], expect: bool, ok: bool): + spec = parse_expectation({"expect_user_requested_search": expect}) + checks, details = deterministic_checks(spec, _turn(calls=calls)) + assert checks == {"search_user_requested": ok} + if not ok: + assert details["search_user_requested"]["expected"] is expect + + +def test_user_requested_search_is_not_read_from_a_string(): + call = _search_call({"keywords": ["x"], "user_requested_search": "true"}) + spec = parse_expectation({"expect_user_requested_search": True}) + assert deterministic_checks(spec, _turn(calls=[call]))[0] == {"search_user_requested": False} + + +def test_widget_objects_are_read_from_the_widget_only(): + spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}"]}) + internal_only = _turn(calls=[_DOC_SEARCH]) + checks, details = deterministic_checks(spec, internal_only) + assert checks == {"search_widget_objects": False} + assert details["search_widget_objects"] == {"missing": [f"document/{_DOC_ID}"], "listed": []} + listed = _turn(calls=[_DOC_SEARCH], widgets=[_widget(("dashboard", "sales"), ("document", _DOC_ID))]) + assert deterministic_checks(spec, listed)[0] == {"search_widget_objects": True} + + +def test_every_widget_object_must_be_listed(): + spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}", "dashboard/sales"]}) + result = _turn(widgets=[_widget(("document", _DOC_ID))]) + checks, details = deterministic_checks(spec, result) + assert checks == {"search_widget_objects": False} + assert details["search_widget_objects"]["missing"] == ["dashboard/sales"] + + +def test_a_widget_object_of_another_type_is_not_the_expected_one(): + spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}"]}) + result = _turn(widgets=[_widget(("dashboard", _DOC_ID))]) + assert deterministic_checks(spec, result)[0] == {"search_widget_objects": False} + + +def test_widget_refs_skip_malformed_objects(): + widget = { + "type": "searchResults", + "objects": [{"id": "a"}, {"type": "document"}, "x", {"id": "b", "type": "document"}], + } + assert widget_refs(_turn(widgets=[widget, {"type": "searchResults", "objects": None}])) == ["document/b"] + + +def test_forbidden_parts_fail_on_a_draft(): + spec = parse_expectation({"forbidden_parts": ["document", "report", "dashboard"]}) + clarify = {"type": "clarifyingQuestions", "questions": []} + assert deterministic_checks(spec, _turn(parts=[clarify]))[0] == {"search_forbidden_parts": True} + draft = {"type": "document", "document": {"title": "Weekly Sales Brief"}} + checks, details = deterministic_checks(spec, _turn(parts=[clarify, draft])) + assert checks == {"search_forbidden_parts": False} + assert details["search_forbidden_parts"] == { + "forbidden": ["document"], + "parts": ["clarifyingQuestions", "document"], + } + + +@pytest.mark.parametrize("value", [["visualization"], ["searchResults"], ["Document"], ["documnet"]]) +def test_forbidden_parts_take_only_part_types_that_reach_the_unhandled_list(value: list[str]): + with pytest.raises(ValueError, match="forbidden_parts"): + parse_expectation({"forbidden_parts": value}) + + +@pytest.mark.parametrize( + ("text", "found"), + [ + ("Open it from the Search list below.", []), + ("See the help page https://www.gooddata.com/docs/cloud/create-reports/.", []), + ("Our site is https://example.com.", []), + ( + "Open https://acme.gooddata.com/workspace/ecommerce_demo/reports/document/abc here.", + ["https://acme.gooddata.com/workspace/ecommerce_demo/reports/document/abc"], + ), + ( + "[Sales](https://acme.gooddata.com/dashboards/#/workspace/ws/dashboard/bf43)", + ["https://acme.gooddata.com/dashboards/#/workspace/ws/dashboard/bf43"], + ), + ("[Weekly brief](/workspace/ws/reports/document/abc)", ["/workspace/ws/reports/document/abc"]), + ( + "Go to ", + ["https://h/api/v1/entities/workspaces/ws/documents/abc"], + ), + ("[Docs](/docs/reports)", []), + ("Read https://www.gooddata.com/docs/cloud/workspaces/overview/ first.", []), + ("[Workspaces](/docs/cloud/workspaces/manage)", []), + ("[Brief]()", ["/workspace/ws/reports/document/abc"]), + ("[Brief]( /workspace/ws/reports/document/abc )", ["/workspace/ws/reports/document/abc"]), + ( + '[Brief](/workspace/ws/reports/document/abc "Weekly brief")', + ["/workspace/ws/reports/document/abc"], + ), + ( + "https://h/metrics/#/workspace/ws/metric/net_sales", + ["https://h/metrics/#/workspace/ws/metric/net_sales"], + ), + ("https://www.gooddata.com/docs/cloud/reports/overview/", []), + ("https://h/analyze/#/ecommerce_demo/viz_1/edit", ["https://h/analyze/#/ecommerce_demo/viz_1/edit"]), + ], +) +def test_object_urls_catch_links_to_workspace_objects(text: str, found: list[str]): + assert object_urls(text) == found + + +def test_no_object_urls_check(): + spec = parse_expectation({"no_object_urls": True}) + assert deterministic_checks(spec, _turn(text="Open it from the list."))[0] == {"search_no_object_urls": True} + link = "https://h/workspace/ws/reports/document/abc" + checks, details = deterministic_checks(spec, _turn(text=f"Here: {link}")) + assert checks == {"search_no_object_urls": False} + assert details["search_no_object_urls"] == {"object_urls": [link]} + + +@pytest.mark.parametrize( + ("expected_output", "message"), + [ + ({"expect_user_requested_search": "yes"}, "expect_user_requested_search"), + ({"widget_objects": []}, "widget_objects"), + ({"widget_objects": ["doc/abc"]}, "expected_objects entry"), + ({"forbidden_parts": "document"}, "forbidden_parts"), + ({"no_object_urls": 1}, "no_object_urls"), + ], +) +def test_malformed_new_options_are_rejected(expected_output: dict, message: str): + with pytest.raises(ValueError, match=message): + parse_expectation(expected_output) + + +def test_search_required_false_with_a_new_check_is_an_item(): + spec = parse_expectation({"search_required": False, "forbidden_parts": ["dashboard"]}) + assert spec.has_turn_checks + + def test_routing_needs_every_required_tool_and_no_forbidden_one(): describe = {"functionName": "get_object_with_children", "functionArguments": "{}"} result = _turn(calls=[_NET_SALES_CALL, describe]) @@ -702,9 +867,15 @@ def test_every_check_is_a_published_score_name(): "answer_rubric": ["Lists net sales"], "expected_limit": 20, "no_raw_ids": True, + "expect_user_requested_search": False, + "widget_objects": ["metric/net_sales"], + "forbidden_parts": ["document"], + "no_object_urls": True, } + turn = _turn(calls=[_NET_SALES_CALL], widgets=[_widget(("metric", "net_sales"))]) + expected["expect_widget"] = True with patch(f"{_MODULE}.score_run", return_value=JudgeVerdict(passed=True, reasoning="ok")): - run, _ = _run(expected, _turn(calls=[_NET_SALES_CALL]), judge=MagicMock()) + run, _ = _run(expected, turn, judge=MagicMock()) assert set(run.checks) == set(SEARCH_CONDITIONAL_SCORES) assert run.passed @@ -868,6 +1039,10 @@ def test_every_check_of_a_report_only_item_is_a_published_diagnostic_name(): "answer_rubric": ["Lists net sales"], "expected_limit": 20, "no_raw_ids": True, + "expect_user_requested_search": True, + "widget_objects": ["metric/net_sales"], + "forbidden_parts": ["document"], + "no_object_urls": True, "report_only": True, } ctx = _scored(expected, JudgeVerdict(passed=True, reasoning="ok"))