Skip to content

Commit 6ec1472

Browse files
committed
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
1 parent 99b56b2 commit 6ec1472

3 files changed

Lines changed: 267 additions & 2 deletions

File tree

‎packages/gooddata-eval/src/gooddata_eval/core/agentic/_search_expectation.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
"no_raw_ids",
3131
"setup_turns",
3232
"report_only",
33+
"expect_user_requested_search",
34+
"widget_objects",
35+
"forbidden_parts",
36+
"no_object_urls",
3337
}
3438
)
3539
_KNOWN_KEYS = SEARCH_OPTION_KEYS | {"tool_call"}
@@ -69,6 +73,25 @@
6973
# a dot or a digit, as the workspace ids have, counts. A one-word id such as metric/revenue is not caught.
7074
_ID_MARK = re.compile(r"[_.0-9]")
7175

76+
# The part types gen-ai streams that land in ``ChatResult.unhandled_parts``. A draft the agent builds
77+
# (document, report, dashboard) is one of them; ``forbidden_parts`` may only name these, so a misspelt
78+
# type cannot read as a pass.
79+
_UNHANDLED_PART_TYPES = frozenset(
80+
{"document", "report", "dashboard", "dashboardPatch", "kda", "whatIf", "clarifyingQuestions"}
81+
)
82+
# A link to a workspace object: an absolute URL, or a markdown link to an app path. The UI opens an object
83+
# from the Search list, so an object URL in the text is one the model wrote itself.
84+
_LINK = re.compile(r"https?://[^\s<>()\[\]\"'`]+|\]\((/[^\s)]+)")
85+
# The routes that open an object: an app route (``/workspace/<ws>/reports/document/<id>``,
86+
# ``/dashboards/#/workspace/<ws>/dashboard/<id>``), the entity API and Analytical Designer
87+
# (``/analyze/#/<ws>/<id>``). A help page with a ``workspaces`` segment is none of them.
88+
_OBJECT_PATH = re.compile(
89+
r"/workspace/[^/\s#?]+/(?:reports?|dashboards?|documents?|visualizations?|metrics?|analyze)\b"
90+
r"|/entities/workspaces/[^/\s]+/"
91+
r"|/analyze/#/[^/\s]+/",
92+
re.IGNORECASE,
93+
)
94+
7295

7396
@dataclass(frozen=True)
7497
class SearchExpectation:
@@ -89,6 +112,10 @@ class SearchExpectation:
89112
no_raw_ids: bool = False
90113
setup_turns: tuple[str, ...] = ()
91114
report_only: bool = False
115+
expect_user_requested_search: bool | None = None
116+
widget_objects: tuple[str, ...] = ()
117+
forbidden_parts: tuple[str, ...] = ()
118+
no_object_urls: bool = False
92119

93120
@property
94121
def has_turn_checks(self) -> bool:
@@ -101,6 +128,10 @@ def has_turn_checks(self) -> bool:
101128
or self.answer_rubric
102129
or self.expected_limit is not None
103130
or self.no_raw_ids
131+
or self.expect_user_requested_search is not None
132+
or self.widget_objects
133+
or self.forbidden_parts
134+
or self.no_object_urls
104135
)
105136

106137
@property
@@ -184,6 +215,15 @@ def parse_expectation(expected_output: Any) -> SearchExpectation:
184215
both = sorted(set(required) & set(forbidden))
185216
if both:
186217
raise ValueError(f"tools {both} are both required and forbidden")
218+
widget_objects: tuple[str, ...] = ()
219+
if "widget_objects" in raw:
220+
widget_objects = _string_list("widget_objects", raw["widget_objects"])
221+
for ref in widget_objects:
222+
_object_ref(ref)
223+
forbidden_parts = _string_list("forbidden_parts", raw["forbidden_parts"]) if "forbidden_parts" in raw else ()
224+
unknown_parts = sorted(set(forbidden_parts) - _UNHANDLED_PART_TYPES)
225+
if unknown_parts:
226+
raise ValueError(f"forbidden_parts {unknown_parts} are not among {sorted(_UNHANDLED_PART_TYPES)}")
187227
limit = raw.get("expected_limit")
188228
if "expected_limit" in raw and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 1):
189229
raise ValueError(f"expected_limit must be a positive integer, got {limit!r}")
@@ -200,6 +240,14 @@ def parse_expectation(expected_output: Any) -> SearchExpectation:
200240
no_raw_ids=_flag("no_raw_ids", raw["no_raw_ids"]) if "no_raw_ids" in raw else False,
201241
setup_turns=_string_list("setup_turns", raw["setup_turns"]) if "setup_turns" in raw else (),
202242
report_only=_flag("report_only", raw["report_only"]) if "report_only" in raw else False,
243+
expect_user_requested_search=(
244+
_flag("expect_user_requested_search", raw["expect_user_requested_search"])
245+
if "expect_user_requested_search" in raw
246+
else None
247+
),
248+
widget_objects=widget_objects,
249+
forbidden_parts=forbidden_parts,
250+
no_object_urls=_flag("no_object_urls", raw["no_object_urls"]) if "no_object_urls" in raw else False,
203251
)
204252
if "tool_call" not in raw and not spec.has_checks:
205253
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]:
274322
return _UUID.findall(outside) + typed
275323

276324

325+
def widget_refs(result: ChatResult) -> list[str]:
326+
"""Every object the turn's ``searchResults`` parts list, as ``type/id``, first sighting first."""
327+
refs: dict[tuple[str, str], str] = {}
328+
for part in result.search_results:
329+
for obj in _objects(part):
330+
object_type, object_id = obj.get("type"), obj.get("id")
331+
if isinstance(object_type, str) and isinstance(object_id, str) and object_type and object_id:
332+
refs.setdefault(_ref_key(object_type, object_id), f"{object_type}/{object_id}")
333+
return list(refs.values())
334+
335+
336+
def object_urls(text: str) -> list[str]:
337+
"""The links in ``text`` that point at a workspace object: absolute URLs and markdown links to app paths."""
338+
found: list[str] = []
339+
for match in _LINK.finditer(text):
340+
link = match.group(1) or match.group(0)
341+
if _OBJECT_PATH.search(link):
342+
found.append(link)
343+
return found
344+
345+
277346
def deterministic_checks(spec: SearchExpectation, result: ChatResult) -> tuple[dict[str, bool], dict[str, Any]]:
278347
"""The checks of one scored turn that need no judge, with the evidence of each failure."""
279348
checks: dict[str, bool] = {}
@@ -307,4 +376,23 @@ def _check(name: str, ok: bool, why: Any) -> None:
307376
if spec.no_raw_ids:
308377
found = raw_ids(result.text_response or "")
309378
_check("search_no_raw_ids", not found, {"raw_ids": found})
379+
if spec.expect_user_requested_search is not None:
380+
flags = [call_args(tc).get("user_requested_search") for tc in search_calls(events)]
381+
asked = any(flag is True for flag in flags)
382+
_check(
383+
"search_user_requested",
384+
asked == spec.expect_user_requested_search,
385+
{"expected": spec.expect_user_requested_search, "user_requested_search": flags},
386+
)
387+
if spec.widget_objects:
388+
listed = widget_refs(result)
389+
missing = missing_objects(spec.widget_objects, listed)
390+
_check("search_widget_objects", not missing, {"missing": missing, "listed": listed[:30]})
391+
if spec.forbidden_parts:
392+
streamed = [part.get("type") for part in result.unhandled_parts]
393+
forbidden = [ptype for ptype in streamed if ptype in spec.forbidden_parts]
394+
_check("search_forbidden_parts", not forbidden, {"forbidden": forbidden, "parts": streamed})
395+
if spec.no_object_urls:
396+
urls = object_urls(result.text_response or "")
397+
_check("search_no_object_urls", not urls, {"object_urls": urls})
310398
return checks, details

‎packages/gooddata-eval/src/gooddata_eval/core/agentic/search_tool.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ def _judge_provider_errors() -> tuple[type[BaseException], ...]:
9191
"search_answer",
9292
"search_limit",
9393
"search_no_raw_ids",
94+
"search_user_requested",
95+
"search_widget_objects",
96+
"search_forbidden_parts",
97+
"search_no_object_urls",
9498
)
9599
# The names a score takes where it does not gate the item: every check of a report_only item, and tool_selection of
96100
# an item with search_required false. A score name then means the same on every item.

‎packages/gooddata-eval/tests/test_agentic_search_tool_checks.py‎

Lines changed: 175 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
SEARCH_OPTION_KEYS,
1818
SearchExpectation,
1919
deterministic_checks,
20+
object_urls,
2021
parse_expectation,
2122
raw_ids,
2223
returned_refs,
24+
widget_refs,
2325
)
2426
from gooddata_eval.core.agentic.search_tool import (
2527
SEARCH_CONDITIONAL_SCORES,
@@ -59,9 +61,16 @@ def _turn(
5961
text: str = "Found 2 results.",
6062
calls: list[dict] | None = None,
6163
widgets: list[dict] | None = None,
64+
parts: list[dict] | None = None,
6265
) -> ChatResult:
6366
return ChatResult.model_validate(
64-
{"textResponse": text, "toolCallEvents": calls or [], "searchResults": widgets or [], "responseId": "resp"}
67+
{
68+
"textResponse": text,
69+
"toolCallEvents": calls or [],
70+
"searchResults": widgets or [],
71+
"unhandledParts": parts or [],
72+
"responseId": "resp",
73+
}
6574
)
6675

6776

@@ -335,6 +344,160 @@ def test_widget(expect: bool, widgets: int, ok: bool):
335344
assert deterministic_checks(parse_expectation({"expect_widget": expect}), result)[0] == {"search_widget": ok}
336345

337346

347+
_DOC_ID = "9a3c8e7e-2f0b-4c55-a1f1-6b0f6a4f1d20"
348+
_DOC_SEARCH = _search_call(
349+
{"keywords": ["Weekly Sales Brief"], "object_types": ["document"], "limit": 10, "user_requested_search": True},
350+
[_obj("document", _DOC_ID)],
351+
)
352+
_DOC_LOOKUP = _search_call(
353+
{"keywords": ["Weekly Sales Brief"], "object_types": ["document"], "limit": 10, "user_requested_search": False},
354+
[_obj("document", _DOC_ID)],
355+
)
356+
357+
358+
@pytest.mark.parametrize(
359+
("calls", "expect", "ok"),
360+
[
361+
([_DOC_SEARCH], True, True),
362+
([_DOC_LOOKUP], True, False),
363+
([_DOC_LOOKUP, _DOC_SEARCH], True, True),
364+
([], True, False),
365+
([_DOC_LOOKUP], False, True),
366+
([_DOC_SEARCH], False, False),
367+
],
368+
)
369+
def test_user_requested_search_reads_every_search_call(calls: list[dict], expect: bool, ok: bool):
370+
spec = parse_expectation({"expect_user_requested_search": expect})
371+
checks, details = deterministic_checks(spec, _turn(calls=calls))
372+
assert checks == {"search_user_requested": ok}
373+
if not ok:
374+
assert details["search_user_requested"]["expected"] is expect
375+
376+
377+
def test_user_requested_search_is_not_read_from_a_string():
378+
call = _search_call({"keywords": ["x"], "user_requested_search": "true"})
379+
spec = parse_expectation({"expect_user_requested_search": True})
380+
assert deterministic_checks(spec, _turn(calls=[call]))[0] == {"search_user_requested": False}
381+
382+
383+
def test_widget_objects_are_read_from_the_widget_only():
384+
spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}"]})
385+
internal_only = _turn(calls=[_DOC_SEARCH])
386+
checks, details = deterministic_checks(spec, internal_only)
387+
assert checks == {"search_widget_objects": False}
388+
assert details["search_widget_objects"] == {"missing": [f"document/{_DOC_ID}"], "listed": []}
389+
listed = _turn(calls=[_DOC_SEARCH], widgets=[_widget(("dashboard", "sales"), ("document", _DOC_ID))])
390+
assert deterministic_checks(spec, listed)[0] == {"search_widget_objects": True}
391+
392+
393+
def test_every_widget_object_must_be_listed():
394+
spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}", "dashboard/sales"]})
395+
result = _turn(widgets=[_widget(("document", _DOC_ID))])
396+
checks, details = deterministic_checks(spec, result)
397+
assert checks == {"search_widget_objects": False}
398+
assert details["search_widget_objects"]["missing"] == ["dashboard/sales"]
399+
400+
401+
def test_a_widget_object_of_another_type_is_not_the_expected_one():
402+
spec = parse_expectation({"widget_objects": [f"document/{_DOC_ID}"]})
403+
result = _turn(widgets=[_widget(("dashboard", _DOC_ID))])
404+
assert deterministic_checks(spec, result)[0] == {"search_widget_objects": False}
405+
406+
407+
def test_widget_refs_skip_malformed_objects():
408+
widget = {
409+
"type": "searchResults",
410+
"objects": [{"id": "a"}, {"type": "document"}, "x", {"id": "b", "type": "document"}],
411+
}
412+
assert widget_refs(_turn(widgets=[widget, {"type": "searchResults", "objects": None}])) == ["document/b"]
413+
414+
415+
def test_forbidden_parts_fail_on_a_draft():
416+
spec = parse_expectation({"forbidden_parts": ["document", "report", "dashboard"]})
417+
clarify = {"type": "clarifyingQuestions", "questions": []}
418+
assert deterministic_checks(spec, _turn(parts=[clarify]))[0] == {"search_forbidden_parts": True}
419+
draft = {"type": "document", "document": {"title": "Weekly Sales Brief"}}
420+
checks, details = deterministic_checks(spec, _turn(parts=[clarify, draft]))
421+
assert checks == {"search_forbidden_parts": False}
422+
assert details["search_forbidden_parts"] == {
423+
"forbidden": ["document"],
424+
"parts": ["clarifyingQuestions", "document"],
425+
}
426+
427+
428+
@pytest.mark.parametrize("value", [["visualization"], ["searchResults"], ["Document"], ["documnet"]])
429+
def test_forbidden_parts_take_only_part_types_that_reach_the_unhandled_list(value: list[str]):
430+
with pytest.raises(ValueError, match="forbidden_parts"):
431+
parse_expectation({"forbidden_parts": value})
432+
433+
434+
@pytest.mark.parametrize(
435+
("text", "found"),
436+
[
437+
("Open it from the Search list below.", []),
438+
("See the help page https://www.gooddata.com/docs/cloud/create-reports/.", []),
439+
("Our site is https://example.com.", []),
440+
(
441+
"Open https://acme.gooddata.com/workspace/ecommerce_demo/reports/document/abc here.",
442+
["https://acme.gooddata.com/workspace/ecommerce_demo/reports/document/abc"],
443+
),
444+
(
445+
"[Sales](https://acme.gooddata.com/dashboards/#/workspace/ws/dashboard/bf43)",
446+
["https://acme.gooddata.com/dashboards/#/workspace/ws/dashboard/bf43"],
447+
),
448+
("[Weekly brief](/workspace/ws/reports/document/abc)", ["/workspace/ws/reports/document/abc"]),
449+
(
450+
"Go to <https://h/api/v1/entities/workspaces/ws/documents/abc>",
451+
["https://h/api/v1/entities/workspaces/ws/documents/abc"],
452+
),
453+
("[Docs](/docs/reports)", []),
454+
("Read https://www.gooddata.com/docs/cloud/workspaces/overview/ first.", []),
455+
("[Workspaces](/docs/cloud/workspaces/manage)", []),
456+
(
457+
'[Brief](/workspace/ws/reports/document/abc "Weekly brief")',
458+
["/workspace/ws/reports/document/abc"],
459+
),
460+
(
461+
"https://h/metrics/#/workspace/ws/metric/net_sales",
462+
["https://h/metrics/#/workspace/ws/metric/net_sales"],
463+
),
464+
("https://www.gooddata.com/docs/cloud/reports/overview/", []),
465+
("https://h/analyze/#/ecommerce_demo/viz_1/edit", ["https://h/analyze/#/ecommerce_demo/viz_1/edit"]),
466+
],
467+
)
468+
def test_object_urls_catch_links_to_workspace_objects(text: str, found: list[str]):
469+
assert object_urls(text) == found
470+
471+
472+
def test_no_object_urls_check():
473+
spec = parse_expectation({"no_object_urls": True})
474+
assert deterministic_checks(spec, _turn(text="Open it from the list."))[0] == {"search_no_object_urls": True}
475+
link = "https://h/workspace/ws/reports/document/abc"
476+
checks, details = deterministic_checks(spec, _turn(text=f"Here: {link}"))
477+
assert checks == {"search_no_object_urls": False}
478+
assert details["search_no_object_urls"] == {"object_urls": [link]}
479+
480+
481+
@pytest.mark.parametrize(
482+
("expected_output", "message"),
483+
[
484+
({"expect_user_requested_search": "yes"}, "expect_user_requested_search"),
485+
({"widget_objects": []}, "widget_objects"),
486+
({"widget_objects": ["doc/abc"]}, "expected_objects entry"),
487+
({"forbidden_parts": "document"}, "forbidden_parts"),
488+
({"no_object_urls": 1}, "no_object_urls"),
489+
],
490+
)
491+
def test_malformed_new_options_are_rejected(expected_output: dict, message: str):
492+
with pytest.raises(ValueError, match=message):
493+
parse_expectation(expected_output)
494+
495+
496+
def test_search_required_false_with_a_new_check_is_an_item():
497+
spec = parse_expectation({"search_required": False, "forbidden_parts": ["dashboard"]})
498+
assert spec.has_turn_checks
499+
500+
338501
def test_routing_needs_every_required_tool_and_no_forbidden_one():
339502
describe = {"functionName": "get_object_with_children", "functionArguments": "{}"}
340503
result = _turn(calls=[_NET_SALES_CALL, describe])
@@ -702,9 +865,15 @@ def test_every_check_is_a_published_score_name():
702865
"answer_rubric": ["Lists net sales"],
703866
"expected_limit": 20,
704867
"no_raw_ids": True,
868+
"expect_user_requested_search": False,
869+
"widget_objects": ["metric/net_sales"],
870+
"forbidden_parts": ["document"],
871+
"no_object_urls": True,
705872
}
873+
turn = _turn(calls=[_NET_SALES_CALL], widgets=[_widget(("metric", "net_sales"))])
874+
expected["expect_widget"] = True
706875
with patch(f"{_MODULE}.score_run", return_value=JudgeVerdict(passed=True, reasoning="ok")):
707-
run, _ = _run(expected, _turn(calls=[_NET_SALES_CALL]), judge=MagicMock())
876+
run, _ = _run(expected, turn, judge=MagicMock())
708877
assert set(run.checks) == set(SEARCH_CONDITIONAL_SCORES)
709878
assert run.passed
710879

@@ -868,6 +1037,10 @@ def test_every_check_of_a_report_only_item_is_a_published_diagnostic_name():
8681037
"answer_rubric": ["Lists net sales"],
8691038
"expected_limit": 20,
8701039
"no_raw_ids": True,
1040+
"expect_user_requested_search": True,
1041+
"widget_objects": ["metric/net_sales"],
1042+
"forbidden_parts": ["document"],
1043+
"no_object_urls": True,
8711044
"report_only": True,
8721045
}
8731046
ctx = _scored(expected, JudgeVerdict(passed=True, reasoning="ok"))

0 commit comments

Comments
 (0)