From 25347b60f3b8963420863479817f35facc109dcd Mon Sep 17 00:00:00 2001 From: huyenthanh09 Date: Wed, 25 Nov 2026 16:10:24 +0700 Subject: [PATCH] fix(gooddata-eval): grade a metric write as read right after the tool call - mcp-server create_metric reads the whole analytics model and writes it back, so concurrent items in one workspace undo each other's writes about a second later. In the 2026-11-23/24 nights this failed 6 of 116 metric_skill_extended runs that read their writes back - ChatClient.send_message takes an optional on_tool_result hook, called in the read loop with each tool call as its result arrives - An options-shape metric run queues a read of each written metric on one background thread from that hook, so the stream, the turn timings and the turn budget stay the agent's. The reads are joined before scoring and before the cleanup - metric_fields_correct and metric_updated grade that read; metric_executes computes the MAQL that was read as an inline measure, on a second thread so no read waits behind an execution, and a metric removed after the read cannot fail it. A read that fails in any way or finds no metric leaves the metric to the read at scoring time, as before. An execution that did not finish runs the written MAQL again, never the stored metric - New diagnostic metric_write_kept: False when a written metric is gone or changed back by scoring time. It never gates - MetricWorkspace.execute_maql shares execute_metric's request, retry and error handling. Listing and reading metrics also turn urllib3 transport errors (MaxRetryError) into WorkspaceReadError - The original shape sends no hook and reads no workspace, as before jira: QA-29907 risk: low Co-Authored-By: Claude Opus 5.5 --- .../core/agentic/_metric_workspace.py | 36 +- .../core/agentic/metric_skill.py | 159 +++++++- .../src/gooddata_eval/core/chat/sse_client.py | 49 ++- .../test_agentic_metric_skill_options.py | 375 +++++++++++++++++- .../gooddata-eval/tests/test_sse_client.py | 35 ++ 5 files changed, 622 insertions(+), 32 deletions(-) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_metric_workspace.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_metric_workspace.py index 41bbc8773..8ef71bd18 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_metric_workspace.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_metric_workspace.py @@ -14,6 +14,7 @@ from typing import Any import httpx +import urllib3.exceptions from gooddata_api_client.exceptions import ApiException, NotFoundException from gooddata_sdk import GoodDataSdk from gooddata_sdk.utils import load_all_entities @@ -69,7 +70,7 @@ def list_metrics(self) -> dict[str, dict]: list_page = functools.partial(self._entities.get_all_entities_metrics, self._ws, _check_return_type=False) try: data = load_all_entities(functools.partial(_page_with_retry, list_page)).data - except (ApiException, httpx.HTTPError, OSError) as exc: + except (ApiException, httpx.HTTPError, urllib3.exceptions.HTTPError, OSError) as exc: raise WorkspaceReadError(f"could not list metrics: {exc}") from exc out: dict[str, dict] = {} for obj in data: @@ -92,7 +93,7 @@ def get_metric(self, metric_id: str) -> dict | None: doc = self._entities.get_entity_metrics(self._ws, metric_id, _check_return_type=False) except NotFoundException: return None - except (ApiException, httpx.HTTPError, OSError) as exc: + except (ApiException, httpx.HTTPError, urllib3.exceptions.HTTPError, OSError) as exc: raise WorkspaceReadError(f"could not read metric {metric_id}: {exc}") from exc # The document is a model even with _check_return_type=False; only its data is a plain dict. data = doc.get("data") if isinstance(doc, dict) else getattr(doc, "data", None) @@ -137,7 +138,7 @@ def _send() -> httpx.Response: return resp.is_success def execute_metric(self, metric_id: str) -> str | None: - """Compute the metric alone; None when it computes, else the reason the platform gave. + """Compute the stored metric alone; None when it computes, else the reason the platform gave. Only a 4xx rejection is a reason. A rate limit (429) or a service fault (5xx) is retried, and one that outlasts the retries is raised: it says nothing about the metric. @@ -146,14 +147,23 @@ def execute_metric(self, metric_id: str) -> str | None: WorkspaceReadError: The request did not reach the platform, the platform did not serve it, or its answer was unreadable. """ + definition = {"measure": {"item": {"identifier": {"id": metric_id, "type": "metric"}}}} + return self._execute(definition, f"metric {metric_id}") + + def execute_maql(self, maql: str) -> str | None: + """Compute a MAQL expression as an inline measure, as ``execute_metric`` does a stored metric. + + It needs no stored metric, so a metric removed after it was read cannot change the answer. + + Raises: + WorkspaceReadError: As for ``execute_metric``. + """ + return self._execute({"inline": {"maql": maql}}, f"MAQL {maql[:80]!r}") + + def _execute(self, definition: dict[str, Any], subject: str) -> str | None: afm = { "execution": { - "measures": [ - { - "localIdentifier": "m", - "definition": {"measure": {"item": {"identifier": {"id": metric_id, "type": "metric"}}}}, - } - ], + "measures": [{"localIdentifier": "m", "definition": definition}], "attributes": [], "filters": [], }, @@ -175,7 +185,7 @@ def _attempt() -> httpx.Response: except _TransientStatus as exc: resp = exc.response if resp.status_code in RETRYABLE_STATUS_CODES or resp.status_code >= 500: - raise WorkspaceReadError(f"could not execute metric {metric_id}: {step} HTTP {resp.status_code}") + raise WorkspaceReadError(f"could not execute {subject}: {step} HTTP {resp.status_code}") return resp try: @@ -190,16 +200,16 @@ def _attempt() -> httpx.Response: links = response.get("links") if isinstance(response, dict) else None result_id = links.get("executionResult") if isinstance(links, dict) else None if not isinstance(result_id, str) or not result_id: - raise WorkspaceReadError(f"could not execute metric {metric_id}: no executionResult in {body!r}"[:400]) + raise WorkspaceReadError(f"could not execute {subject}: no executionResult in {body!r}"[:400]) result = _served("result", lambda: self._client.get(f"{url}/result/{result_id}", headers=self._auth)) if not result.is_success: return f"result: HTTP {result.status_code} {result.text[:300]}" computed = result.json() except (httpx.HTTPError, ValueError) as exc: - raise WorkspaceReadError(f"could not execute metric {metric_id}: {type(exc).__name__}: {exc}") from exc + raise WorkspaceReadError(f"could not execute {subject}: {type(exc).__name__}: {exc}") from exc if not isinstance(computed, dict) or not isinstance(computed.get("data"), list): # A computed result carries its data list, empty or not; a 200 without one proves no computation. - raise WorkspaceReadError(f"could not execute metric {metric_id}: no data list in {str(computed)[:200]}") + raise WorkspaceReadError(f"could not execute {subject}: no data list in {str(computed)[:200]}") return None def conversation_items(self, conversation_id: str) -> list[dict[str, Any]]: diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/metric_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/metric_skill.py index 028cba861..dbcd08c60 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/metric_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/metric_skill.py @@ -7,6 +7,7 @@ import re import time from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass, field from typing import Any @@ -97,7 +98,8 @@ def _judge_provider_errors() -> tuple[type[BaseException], ...]: # Every check score an options-shape item can publish, beside metric_created and maql_correct. Each is published only # for an item that opts into it; metric_scored only when the snapshot or the restore failed. A check the harness could # not read reads False with a "harness:" reason; a run left without a verdict by it is labelled ERROR. -# metric_first_proposal_correct is a diagnostic and never gates. +# The diagnostics never gate: metric_first_proposal_correct, and metric_write_kept, which reads False when a metric the +# agent wrote was gone or changed back by scoring time (see _WriteReadback). METRIC_CONDITIONAL_SCORES = ( "metric_not_created", "metric_reuse_named", @@ -113,7 +115,7 @@ def _judge_provider_errors() -> tuple[type[BaseException], ...]: "metric_suggestions", "metric_scored", ) -METRIC_DIAGNOSTIC_SCORES = ("metric_first_proposal_correct",) +METRIC_DIAGNOSTIC_SCORES = ("metric_first_proposal_correct", "metric_write_kept") _RUBRIC_STEPS = [ "EXPECTED OUTPUT states the criteria the assistant's behaviour must meet.", @@ -335,6 +337,131 @@ def _successful_writes(tool_call_events: list[ToolCallEvent]) -> list[dict]: return out +def _metric_state(attributes: dict | None) -> dict | None: + """The fields of a stored metric a write sets, to compare two reads of it; None for a missing metric.""" + if attributes is None: + return None + content = attributes.get("content") or {} + return { + "title": attributes.get("title") or "", + "description": attributes.get("description") or "", + "tags": sorted(attributes.get("tags") or []), + "format": content.get("format") or "", + "maql": content.get("maql") or "", + } + + +def _stored_maql(attributes: dict | None) -> str | None: + """The MAQL of a stored metric, or None when there is no metric or no MAQL.""" + maql = ((attributes or {}).get("content") or {}).get("maql") + return maql if isinstance(maql, str) and maql else None + + +@dataclass +class _WriteReadback: + """Each metric as stored right after the agent's latest write to it, read while the turn still streams. + + ``create_metric`` reads the whole analytics model and writes it back, so a concurrent write in the same workspace + can undo this one about a second later. Reading at once scores what the agent wrote, not that race. The read at + scoring time then only tells whether the write was kept (``metric_write_kept``). + + The reads run on one background thread, in write order, so the stream is never held up and the turn's timings and + budgets stay the agent's. Executions of the MAQL that was read run on a second thread, so no read waits behind a + slow execution; each runs inline, so a metric removed after the read cannot fail it. ``wait`` joins both before + anything reads ``stored`` or ``executions``. + + A metric missing here is read at scoring time instead, as before: the read failed or found no metric, or the chat + client did not stream the turn. + """ + + workspace: MetricWorkspace + execute: bool + stored: dict[str, dict] = field(default_factory=dict) + # The answer of each MAQL executed, by its text: an execution that ends after a later write cannot stand for it. + executions: dict[str, str | None] = field(default_factory=dict) + _reads: ThreadPoolExecutor | None = None + _runs: ThreadPoolExecutor | None = None + _pending_reads: list[Future[None]] = field(default_factory=list) + _pending_runs: list[Future[None]] = field(default_factory=list) + + def on_tool_result(self, event: dict[str, Any]) -> None: + """Queue a read of the metric a successful ``create_metric`` call wrote. Never raises: it runs in the stream.""" + try: + if event.get("functionName") != "create_metric": + return + writes = _successful_writes([ToolCallEvent.model_validate(event)]) + metric_id = writes[0].get("metric_id") if writes else None + if not isinstance(metric_id, str) or not metric_id: + return + if self._reads is None: + self._reads = ThreadPoolExecutor(max_workers=1, thread_name_prefix="metric-readback") + self._pending_reads.append(self._reads.submit(self._read_back, metric_id)) + except Exception as exc: + print(f"[READBACK] Could not queue the read-back of a create_metric result: {type(exc).__name__}: {exc}") + + def _read_back(self, metric_id: str) -> None: + # A failed read after a later write must not leave the earlier write's state behind. + self.stored.pop(metric_id, None) + metric = self.workspace.get_metric(metric_id) + if metric is None: + return + self.stored[metric_id] = metric + maql = _stored_maql(metric) + if self.execute and maql: + if self._runs is None: + self._runs = ThreadPoolExecutor(max_workers=1, thread_name_prefix="metric-execute") + self._pending_runs.append(self._runs.submit(self._execute, maql)) + + def _execute(self, maql: str) -> None: + self.executions[maql] = self.workspace.execute_maql(maql) + + def wait(self) -> None: + """Let every queued read and execution finish; one that raised leaves its metric to scoring time.""" + # Reads first: a read queues the execution of what it read. + for pending in (self._pending_reads, self._pending_runs): + for future in pending: + try: + future.result() + except Exception as exc: + print(f"[READBACK] A read-back failed; scoring reads it again: {type(exc).__name__}: {exc}") + pending.clear() + + def close(self) -> None: + self.wait() + for pool in (self._reads, self._runs): + if pool is not None: + pool.shutdown() + self._reads = self._runs = None + + def metric(self, metric_id: str) -> dict | None: + """The metric as written; read now when no read was taken at write time.""" + if metric_id in self.stored: + return self.stored[metric_id] + return self.workspace.get_metric(metric_id) + + def execution_error(self, metric_id: str) -> str | None: + """Why the metric did not compute as written, or None; computed now when it was not at write time. + + A metric read at write time whose execution did not finish computes that MAQL again, never the stored metric, + which a concurrent writer may have replaced by then. + """ + maql = _stored_maql(self.stored.get(metric_id)) + if maql is None: + return self.workspace.execute_metric(metric_id) + if maql in self.executions: + return self.executions[maql] + return self.workspace.execute_maql(maql) + + def changed_since_write(self) -> dict[str, Any]: + """The metrics whose stored state differs from the read taken right after their write, with both states.""" + changed: dict[str, Any] = {} + for metric_id, written in self.stored.items(): + now = _metric_state(self.workspace.get_metric(metric_id)) + if now != _metric_state(written): + changed[metric_id] = {"after_write": _metric_state(written), "at_scoring": now} + return changed + + class MetricMatchUndecided(RuntimeError): """The assignment search ran out of steps before it could tell whether every expected metric was written.""" @@ -483,12 +610,16 @@ def _score_options_run( before: dict[str, dict], judge: LLMJudge | None, answered: bool = True, + readback: _WriteReadback | None = None, ) -> tuple[dict[str, bool], dict[str, bool], dict[str, Any], str | None, list[str]]: """The gating checks, diagnostics, failure reasons, harness error and unscored check names of one run. A check the harness could not evaluate (the workspace or the conversation was unreadable, the judge gave no verdict) reads False, is named unscored and sets the harness error; the other checks are still evaluated. + The stored fields and the execution of a written metric are graded on ``readback``, taken right after the write. """ + readback = readback or _WriteReadback(workspace, execute=False) + readback.wait() checks: dict[str, bool] = {} diagnostics: dict[str, bool] = {} details: dict[str, Any] = {} @@ -569,7 +700,7 @@ def _fields() -> None: if target_id is None: _check("metric_fields_correct", False, "no metric was written") else: - mismatches = field_mismatches(fields, target_id, workspace.get_metric(target_id)) + mismatches = field_mismatches(fields, target_id, readback.metric(target_id)) _check("metric_fields_correct", not mismatches, mismatches) _read("metric_fields_correct", _fields) @@ -577,7 +708,7 @@ def _fields() -> None: update = spec.expected_update def _update() -> None: - mismatches = update_mismatches(update, before.get(update.metric_id), workspace.get_metric(update.metric_id)) + mismatches = update_mismatches(update, before.get(update.metric_id), readback.metric(update.metric_id)) _check("metric_updated", not mismatches, mismatches) _read("metric_updated", _update) @@ -591,7 +722,7 @@ def _no_deletion() -> None: if spec.expect_executes: def _executes() -> None: - reason = workspace.execute_metric(target_id) if target_id else "no metric was written" + reason = readback.execution_error(target_id) if target_id else "no metric was written" _check("metric_executes", reason is None, reason) _read("metric_executes", _executes) @@ -633,6 +764,15 @@ def _suggestions() -> None: ) if not diagnostics["metric_first_proposal_correct"]: details["metric_first_proposal_correct"] = {"proposed": proposed} + if readback.stored: + try: + changed = readback.changed_since_write() + except WorkspaceReadError as exc: + print(f"[READBACK] Could not check that the written metrics were kept: {exc}") + else: + diagnostics["metric_write_kept"] = not changed + if changed: + details["metric_write_kept"] = changed return checks, diagnostics, details, ("; ".join(harness_errors) or None), unscored @@ -736,6 +876,9 @@ def _execute_single_metric_run( writes: list[dict] = [] answered_turns = 0 result: MetricRunResult | None = None + readback = _WriteReadback(workspace, execute=spec.expect_executes) if workspace is not None else None + # Only an options-shape run reads its writes back; the original shape sends exactly as before. + send_options: dict[str, Any] = {"on_tool_result": readback.on_tool_result} if readback is not None else {} def _record_turn(result: ChatResult, events: list[ToolCallEvent]) -> str: """Note the turn's writes and text for the options-shape checks; returns the rendered text.""" @@ -759,7 +902,7 @@ def _record_turn(result: ChatResult, events: list[ToolCallEvent]) -> str: turns += 1 agent_started = time.monotonic() try: - chat_result = client.send_message(conversation_id, current_question) + chat_result = client.send_message(conversation_id, current_question, **send_options) except ChatError as exc: # Without this the exception escapes run_agentic_metric_skill entirely, # discarding every K-run already completed along with any exit_reason. A @@ -876,6 +1019,7 @@ def _record_turn(result: ChatResult, events: list[ToolCallEvent]) -> str: before=before, judge=judge, answered=answered_turns > 0, + readback=readback, ) result = MetricRunResult( conversation_id=conversation_id, @@ -901,6 +1045,9 @@ def _record_turn(result: ChatResult, events: list[ToolCallEvent]) -> str: ) return result finally: + if readback is not None: + # Joined before the cleanup, so no read-back runs against the workspace while it is put back. + readback.close() for metric_id in created_metric_ids: _delete_metric(sdk, workspace_id, metric_id) if workspace is not None: diff --git a/packages/gooddata-eval/src/gooddata_eval/core/chat/sse_client.py b/packages/gooddata-eval/src/gooddata_eval/core/chat/sse_client.py index a278c3d48..700b56fa9 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/chat/sse_client.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/chat/sse_client.py @@ -20,7 +20,7 @@ import re import time from dataclasses import dataclass, field -from typing import Any, Iterable +from typing import Any, Callable, Iterable from urllib.parse import quote import httpx @@ -59,6 +59,10 @@ # where the agent's create_adhoc_visualization call failed and only its arguments survive. ADHOC_VIZ_ID = "adhoc-visualization-not-persisted" +# Called with a tool-call event (camelCase, as in ``ChatResult.tool_call_events``) as soon as its result arrives, +# while the turn still streams. It runs in the read loop, so it must return at once and must not raise. +ToolResultHook = Callable[[dict[str, Any]], None] + _KNOWN_PART_TYPES: frozenset[str] = frozenset( { "text", @@ -282,12 +286,14 @@ def _handle_tool_call(content: dict[str, Any], acc: _SseAccumulator) -> None: acc.adhoc_viz_args.append(viz) -def _handle_tool_result(content: dict[str, Any], acc: _SseAccumulator) -> None: +def _handle_tool_result(content: dict[str, Any], acc: _SseAccumulator, on_tool_result: ToolResultHook | None) -> None: call_id = content.get("callId", "") idx = acc.call_id_to_event_index.get(call_id) if idx is not None: acc.tool_call_events[idx]["result"] = content.get("result", "") acc.tool_call_events[idx]["result_ts"] = round(time.monotonic() - acc.t0, 3) + if on_tool_result is not None: + on_tool_result(dict(acc.tool_call_events[idx])) def _build_chat_result(acc: _SseAccumulator) -> ChatResult: @@ -373,8 +379,11 @@ def _until_deadline( yield line -def parse_sse_lines(lines: Iterable[str]) -> ChatResult: - """Parse an SSE stream (iterable of decoded lines) into a ChatResult.""" +def parse_sse_lines(lines: Iterable[str], on_tool_result: ToolResultHook | None = None) -> ChatResult: + """Parse an SSE stream (iterable of decoded lines) into a ChatResult. + + ``on_tool_result`` is called with each tool call as soon as its result arrives; see ``ToolResultHook``. + """ acc = _SseAccumulator() current_event = "message" # SSE default in the absence of an explicit "event: " line it = iter(lines) @@ -467,7 +476,7 @@ def parse_sse_lines(lines: Iterable[str]) -> ChatResult: elif ctype == "toolCall": _handle_tool_call(content, acc) elif role == "tool" and ctype == "toolResult": - _handle_tool_result(content, acc) + _handle_tool_result(content, acc, on_tool_result) return _build_chat_result(acc) @@ -612,9 +621,24 @@ def delete_conversation(self, conversation_id: str) -> None: pass # best-effort cleanup def send_message( - self, conversation_id: str, question: str, *, user_context: dict[str, Any] | None = None + self, + conversation_id: str, + question: str, + *, + user_context: dict[str, Any] | None = None, + on_tool_result: ToolResultHook | None = None, ) -> ChatResult: - return self._send(conversation_id, {"type": "text", "text": question}, user_context=user_context) + """Send one user message and return the parsed turn. + + ``on_tool_result`` sees each tool call as soon as its result arrives, before the turn ends; a retried attempt + calls it again for the calls it repeats. It runs in the read loop: work that takes time belongs elsewhere. + """ + return self._send( + conversation_id, + {"type": "text", "text": question}, + user_context=user_context, + on_tool_result=on_tool_result, + ) def send_clarifying_answers( self, @@ -632,7 +656,12 @@ def send_clarifying_answers( return self._send(conversation_id, content, user_context=user_context) def _send( - self, conversation_id: str, content: dict[str, Any], *, user_context: dict[str, Any] | None = None + self, + conversation_id: str, + content: dict[str, Any], + *, + user_context: dict[str, Any] | None = None, + on_tool_result: ToolResultHook | None = None, ) -> ChatResult: url = f"{self._base}/{conversation_id}/messages" join_headers, joined = self._join_item_trace(conversation_id) @@ -662,7 +691,9 @@ def _do() -> ChatResult: with self._client.stream("POST", url, json=body, headers=headers) as resp: resp.raise_for_status() try: - result = parse_sse_lines(_until_deadline(resp.iter_lines(), deadline, budget, scope)) + result = parse_sse_lines( + _until_deadline(resp.iter_lines(), deadline, budget, scope), on_tool_result + ) except ChatError as exc: if exc.partial_result is not None: exc.partial_result.turn_wall_clock_sec = time.monotonic() - t0 diff --git a/packages/gooddata-eval/tests/test_agentic_metric_skill_options.py b/packages/gooddata-eval/tests/test_agentic_metric_skill_options.py index 7ec3c50d4..520bee09b 100644 --- a/packages/gooddata-eval/tests/test_agentic_metric_skill_options.py +++ b/packages/gooddata-eval/tests/test_agentic_metric_skill_options.py @@ -4,13 +4,16 @@ import json import sys +import threading import types from collections.abc import Callable, Iterator, Sequence +from concurrent.futures import Future from contextlib import contextmanager from typing import Any from unittest.mock import MagicMock, patch import pytest +import urllib3.exceptions from gooddata_api_client.exceptions import ApiException, NotFoundException from gooddata_eval.core.agentic import _metric_workspace as mw from gooddata_eval.core.agentic import metric_skill as metric_skill_mod @@ -246,6 +249,8 @@ def __init__(self, metrics: dict[str, dict]) -> None: self.restored: list[tuple[str, bool]] = [] self.items: list[dict] = [] self.execute_error: str | None = None + self.maql_error: str | None = None + self.executed_maql: list[str] = [] self.read_error: str | None = None self.snapshot_error: str | None = None self.restore_fails = False @@ -271,6 +276,10 @@ def restore_metric(self, metric_id: str, attributes: dict, *, exists: bool) -> b def execute_metric(self, metric_id: str) -> str | None: return self.execute_error + def execute_maql(self, maql: str) -> str | None: + self.executed_maql.append(maql) + return self.maql_error + def conversation_items(self, conversation_id: str) -> list[dict]: if self.read_error: raise WorkspaceReadError(self.read_error) @@ -280,21 +289,57 @@ def close(self) -> None: pass +class _InlineExecutor: + """Runs each queued read-back at once, so a test decides when it happens relative to the rest of the turn.""" + + def __init__(self, *_args: Any, **_kwargs: Any) -> None: + pass + + def submit(self, fn: Callable[..., None], *args: Any) -> Future[None]: + future: Future[None] = Future() + try: + future.set_result(fn(*args)) + except Exception as exc: + future.set_exception(exc) + return future + + def shutdown(self) -> None: + pass + + @contextmanager def _run_env( - turns: Sequence[ChatResult | Exception], workspace: _FakeWorkspace, *, on_send: Callable[[str], None] | None = None + turns: Sequence[ChatResult | Exception], + workspace: _FakeWorkspace, + *, + on_send: Callable[[str], None] | None = None, + after_turn: Callable[[], None] | None = None, + real_threads: bool = False, ) -> Iterator[tuple[MagicMock, MagicMock]]: - """Patch the chat client to answer ``turns`` in order (an exception is raised), and the other collaborators.""" + """Patch the chat client to answer ``turns`` in order (an exception is raised), and the other collaborators. + + ``after_turn`` runs once the turn's tool results have streamed, as a concurrent writer would. Read-backs run + inline as each result streams, unless ``real_threads`` keeps the background thread. + """ client = MagicMock() client.create_conversation.return_value = "conv-1" answers = iter(turns) - def _send(_conversation_id: str, message: str) -> ChatResult: + def _send( + _conversation_id: str, message: str, *, on_tool_result: Callable[[dict], None] | None = None + ) -> ChatResult: if on_send: on_send(message) answer = next(answers) + streamed = answer.partial_result if isinstance(answer, ChatError) else answer + if on_tool_result is not None and isinstance(streamed, ChatResult): + # The real client calls the hook as each result streams in, before the turn ends or breaks. + for event in streamed.tool_call_events: + on_tool_result(event.model_dump(by_alias=True)) if isinstance(answer, Exception): raise answer + if after_turn: + after_turn() return answer client.send_message.side_effect = _send @@ -303,6 +348,11 @@ def _send(_conversation_id: str, message: str) -> ChatResult: patch("gooddata_eval.core.agentic.metric_skill.GoodDataSdk"), patch("gooddata_eval.core.agentic.metric_skill.MetricWorkspace", return_value=workspace), patch("gooddata_eval.core.agentic.metric_skill.generate_simulated_response") as sim, + patch.object( + metric_skill_mod, + "ThreadPoolExecutor", + metric_skill_mod.ThreadPoolExecutor if real_threads else _InlineExecutor, + ), ): yield client, sim @@ -534,6 +584,298 @@ def _delete(_message: str) -> None: assert ws.restored == [("net_sales", False)] +_WRITTEN = {"title": "Return Margin", "content": {"format": "#,##0.00", "maql": "SELECT 1"}} + + +def _write_then(after: Callable[[_FakeWorkspace], None]) -> tuple[AgenticMetricSummary, _FakeWorkspace]: + """Run one turn that writes metric ``m``; ``after`` changes the workspace once the turn has streamed.""" + ws = _FakeWorkspace({}) + + def _create(_message: str) -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + + turn = _turn("Created.", {"metric_id": "m", "maql": "SELECT 1"}) + with _run_env([turn], ws, on_send=_create, after_turn=lambda: after(ws)): + summary = _run( + {"candidates": ["SELECT 1"], "expect_executes": True, "expected_fields": {"title": "Return Margin"}} + ) + return summary, ws + + +def test_a_kept_write_is_graded_and_reported_as_kept() -> None: + summary, _ = _write_then(lambda ws: None) + assert summary.pass_at_k and all(summary.best.checks.values()) + assert summary.best.diagnostics == {"metric_write_kept": True} + + +def test_a_write_lost_after_its_turn_is_graded_as_written_and_reported() -> None: + # A concurrent create_metric wrote back a model read before this write: the metric is gone and cannot compute. + def _lose(ws: _FakeWorkspace) -> None: + ws.metrics.pop("m") + ws.execute_error = "execute: HTTP 400 metric m not found" + + summary, _ = _write_then(_lose) + assert summary.best.checks == { + "metric_created": True, + "maql_correct": True, + "metric_fields_correct": True, + "metric_executes": True, + } + assert summary.pass_at_k and summary.best.harness_error is None + assert summary.best.diagnostics == {"metric_write_kept": False} + assert summary.best.check_details["metric_write_kept"]["m"]["at_scoring"] is None + + +def test_the_written_maql_is_executed_inline_and_a_failure_fails_the_check() -> None: + ws = _FakeWorkspace({}) + ws.maql_error = "execute: HTTP 400 Objects [Identifier(no_such_fact)] are either inaccessible or not existing." + + def _create(_message: str) -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + + with _run_env([_turn("Created.", {"metric_id": "m", "maql": "SELECT 1"})], ws, on_send=_create): + summary = _run({"candidates": ["SELECT 1"], "expect_executes": True}) + assert ws.executed_maql == ["SELECT 1"] + assert summary.best.checks["metric_executes"] is False + assert "no_such_fact" in summary.best.check_details["metric_executes"] + + +def test_a_metric_not_found_right_after_its_write_is_read_again_at_scoring() -> None: + ws = _FakeWorkspace({}) + + def _appear() -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + + turn = _turn("Created.", {"metric_id": "m", "maql": "SELECT 1"}) + with _run_env([turn], ws, after_turn=_appear): + summary = _run({"candidates": ["SELECT 1"], "expected_fields": {"title": "Return Margin"}}) + assert summary.best.checks["metric_fields_correct"] is True + assert summary.best.diagnostics == {} + + +def test_an_update_undone_after_its_turn_is_graded_as_written_and_reported() -> None: + ws = _FakeWorkspace({"average_product_cost": _AVG_COST}) + + def _rename(message: str) -> None: + if message == "Yes, go ahead.": + ws.metrics["average_product_cost"] = {**_AVG_COST, "title": "Avg Unit Cost"} + + def _undo() -> None: + ws.metrics["average_product_cost"] = json.loads(json.dumps(_AVG_COST)) + + write = {"metric_id": "average_product_cost", "maql": "SELECT AVG({fact/order_unit_cost})", "created_new": False} + with _run_env([_turn("Rename it?"), _turn("Renamed.", write)], ws, on_send=_rename, after_turn=_undo): + summary = _run( + { + "expected_update": {"metric_id": "average_product_cost", "title": "Avg Unit Cost"}, + "user_replies": ["Yes, go ahead."], + } + ) + assert summary.best.checks == {"metric_updated": True} + lost = summary.best.check_details["metric_write_kept"]["average_product_cost"] + assert (lost["after_write"]["title"], lost["at_scoring"]["title"]) == ("Avg Unit Cost", "Average Product Cost") + + +def test_a_write_the_harness_could_not_read_at_once_is_read_at_scoring() -> None: + ws = _FakeWorkspace({}) + + def _create(_message: str) -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + ws.read_error = "could not read metric m: timeout" + + def _recover() -> None: + ws.read_error = None + + turn = _turn("Created.", {"metric_id": "m", "maql": "SELECT 1"}) + with _run_env([turn], ws, on_send=_create, after_turn=_recover): + summary = _run({"candidates": ["SELECT 1"], "expected_fields": {"title": "Return Margin"}}) + assert summary.best.checks["metric_fields_correct"] is True + assert summary.best.harness_error is None + assert summary.best.diagnostics == {} + + +def test_only_create_metric_results_are_read_back_and_an_unstored_write_is_not_compared() -> None: + ws = _FakeWorkspace({}) + + def _create(_message: str) -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + + turn = ChatResult.model_validate( + { + "textResponse": "Created.", + "toolCallEvents": [ + {"functionName": "search_objects", "functionArguments": "{}", "result": "{}"}, + { + "functionName": "create_metric", + "functionArguments": "{}", + "result": json.dumps({"data": {"metric_id": "x", "maql": "SELECT 2"}}), + }, + { + "functionName": "create_metric", + "functionArguments": "{}", + "result": json.dumps({"data": {"metric_id": "m", "maql": "SELECT 1"}}), + }, + ], + } + ) + with _run_env([turn], ws, on_send=_create): + summary = _run({"candidates": ["SELECT 1"], "expected_fields": {"title": "Return Margin"}}) + # x was never stored, so there is no written state to compare with. + assert summary.best.checks["metric_fields_correct"] is True + assert summary.best.diagnostics == {"metric_write_kept": True} + + +def test_an_unreadable_workspace_at_scoring_leaves_out_only_the_kept_diagnostic() -> None: + boom = WorkspaceReadError("could not read metric m: timeout") + with patch.object(metric_skill_mod._WriteReadback, "changed_since_write", side_effect=boom): + summary, _ = _write_then(lambda ws: None) + assert summary.pass_at_k and summary.best.harness_error is None + assert summary.best.diagnostics == {} + + +class _BrokenExecutionWorkspace(_FakeWorkspace): + """The first inline execution fails in transport.""" + + def execute_maql(self, maql: str) -> str | None: + if not self.executed_maql: + self.executed_maql.append(maql) + raise WorkspaceReadError("could not execute MAQL: ReadTimeout") + return super().execute_maql(maql) + + +def test_an_unfinished_execution_computes_the_written_maql_again_not_the_stored_metric() -> None: + ws = _BrokenExecutionWorkspace({}) + ws.maql_error = "execute: HTTP 400 Objects [Identifier(no_such_fact)] are either inaccessible or not existing." + + def _create(_message: str) -> None: + ws.metrics["m"] = json.loads(json.dumps(_WRITTEN)) + + def _replace() -> None: + # A concurrent writer replaces the metric, and the replacement computes by id. + ws.metrics["m"] = {**_WRITTEN, "content": {**_WRITTEN["content"], "maql": "SELECT 2"}} + + turn = _turn("Created.", {"metric_id": "m", "maql": "SELECT 1"}) + with _run_env([turn], ws, on_send=_create, after_turn=_replace): + summary = _run({"candidates": ["SELECT 1"], "expect_executes": True}) + assert ws.executed_maql == ["SELECT 1", "SELECT 1"] + assert summary.best.checks["metric_executes"] is False + + +_GATE_S = 2.0 # Only stops a hung test; every gate below opens as soon as its condition holds. + + +class _GatedWorkspace(_FakeWorkspace): + """A metric read waits until ``released`` opens, and notes whether it opened and on which thread the read ran.""" + + def __init__(self, metrics: dict[str, dict]) -> None: + super().__init__(metrics) + self.released = threading.Event() + self.reads: list[tuple[str, bool]] = [] + + def get_metric(self, metric_id: str) -> dict | None: + if threading.current_thread() is not threading.main_thread(): + self.reads.append((threading.current_thread().name, self.released.wait(_GATE_S))) + return super().get_metric(metric_id) + + +def test_read_backs_run_off_the_stream_and_are_joined_before_scoring() -> None: + ws = _GatedWorkspace({"m": _WRITTEN}) + turn = _turn("Created.", {"metric_id": "m", "maql": "SELECT 1"}) + # The gate opens only after the hook has returned: a read inside the hook would time out first. + with _run_env([turn], ws, after_turn=ws.released.set, real_threads=True): + summary = _run({"candidates": ["SELECT 1"], "expected_fields": {"title": "Return Margin"}}) + assert len(ws.reads) == 1 + thread, opened = ws.reads[0] + assert thread.startswith("metric-readback") and opened + assert summary.best.checks["metric_fields_correct"] is True + assert summary.best.diagnostics == {"metric_write_kept": True} + + +class _SlowExecutionWorkspace(_FakeWorkspace): + """The first write's execution holds until ``release`` opens; each read notes when it ran.""" + + def __init__(self, metrics: dict[str, dict]) -> None: + super().__init__(metrics) + self.release = threading.Event() + self.second_read = threading.Event() + self.read_before_removal = False + + def get_metric(self, metric_id: str) -> dict | None: + found = super().get_metric(metric_id) + if metric_id == "m2" and threading.current_thread() is not threading.main_thread(): + self.second_read.set() + return found + + def execute_maql(self, maql: str) -> str | None: + if maql == "SELECT 1": + # Held longer than the test waits for the second read, so a read queued behind it is seen as late. + self.release.wait(2 * _GATE_S) + return super().execute_maql(maql) + + +def test_a_read_does_not_wait_behind_an_earlier_writes_execution() -> None: + m2 = {**_WRITTEN, "title": "Second", "content": {**_WRITTEN["content"], "maql": "SELECT 2"}} + ws = _SlowExecutionWorkspace({"m1": _WRITTEN, "m2": m2}) + + def _lose_second_then_release() -> None: + # m2 is read while m1's execution still holds, then a concurrent writer removes m2. + ws.read_before_removal = ws.second_read.wait(_GATE_S) + ws.metrics.pop("m2") + ws.release.set() + + turn = _turn("Created both.", {"metric_id": "m1", "maql": "SELECT 1"}, {"metric_id": "m2", "maql": "SELECT 2"}) + with _run_env([turn], ws, after_turn=_lose_second_then_release, real_threads=True): + summary = _run({"candidates": ["SELECT 2"], "expect_executes": True, "expected_fields": {"title": "Second"}}) + assert ws.read_before_removal + assert summary.best.checks == { + "metric_created": True, + "maql_correct": True, + "metric_fields_correct": True, + "metric_executes": True, + } + assert summary.best.check_details["metric_write_kept"]["m2"]["at_scoring"] is None + + +class _FlakyWorkspace(_FakeWorkspace): + """The first metric read fails the way a connection error from the API client does: not a WorkspaceReadError.""" + + def __init__(self, metrics: dict[str, dict]) -> None: + super().__init__(metrics) + self.failed = False + + def get_metric(self, metric_id: str) -> dict | None: + if not self.failed: + self.failed = True + raise RuntimeError("MaxRetryError: connection refused") + return super().get_metric(metric_id) + + +def test_a_read_back_that_raises_any_error_leaves_the_metric_to_the_scoring_read() -> None: + ws = _FlakyWorkspace({"m": _WRITTEN}) + with _run_env([_turn("Created.", {"metric_id": "m", "maql": "SELECT 1"})], ws): + summary = _run({"candidates": ["SELECT 1"], "expected_fields": {"title": "Return Margin"}}) + assert ws.failed and summary.best.checks["metric_fields_correct"] is True + assert summary.best.harness_error is None and summary.best.diagnostics == {} + + +def test_the_hook_never_raises_on_an_unreadable_event() -> None: + readback = metric_skill_mod._WriteReadback(_FakeWorkspace({}), execute=False) + readback.on_tool_result({"functionName": "create_metric"}) # no functionArguments: the event does not validate + readback.close() + assert readback.stored == {} + + +def test_the_original_shape_sends_no_tool_result_hook() -> None: + with ( + patch("gooddata_eval.core.agentic.metric_skill.ChatClient") as chat_cls, + patch("gooddata_eval.core.agentic.metric_skill.GoodDataSdk"), + ): + send = chat_cls.return_value.send_message + send.return_value = _turn("ok", {"maql": "SELECT 1", "metric_id": "m"}) + run_agentic_metric_skill("http://h", "t", "ws", "q", [{"maql": "SELECT 1"}], k=1, max_iterations=1) + assert send.call_args.kwargs == {} + + def test_every_published_check_name_is_listed_for_the_report() -> None: names = { "metric_not_created", @@ -551,7 +893,7 @@ def test_every_published_check_name_is_listed_for_the_report() -> None: "metric_scored", } assert set(METRIC_CONDITIONAL_SCORES) == names - assert METRIC_DIAGNOSTIC_SCORES == ("metric_first_proposal_correct",) + assert METRIC_DIAGNOSTIC_SCORES == ("metric_first_proposal_correct", "metric_write_kept") def _evaluate( @@ -1111,6 +1453,19 @@ def _boom(request: mw.httpx.Request) -> mw.httpx.Response: assert _http_workspace(_boom).restore_metric("net_sales", _NET_SALES, exists=True) is False +def test_a_urllib3_connection_failure_is_a_read_error_for_listing_and_lookup(_no_backoff: None) -> None: + # The generated entities API raises urllib3's MaxRetryError once its own retries are spent; listing retries it too. + refused = urllib3.exceptions.MaxRetryError(None, "/api/v1/entities", reason="connection refused") + sdk = _fake_sdk() + sdk._client.entities_api.get_all_entities_metrics.side_effect = refused + sdk._client.entities_api.get_entity_metrics.side_effect = refused + ws = mw.MetricWorkspace("http://h", "t", "ws", sdk) + with pytest.raises(WorkspaceReadError, match="could not list metrics"): + ws.list_metrics() + with pytest.raises(WorkspaceReadError, match="could not read metric m"): + ws.get_metric("m") + + def test_listing_or_reading_metrics_wraps_api_failures() -> None: sdk = _fake_sdk() sdk._client.entities_api.get_all_entities_metrics.side_effect = ApiException(status=400) @@ -1155,6 +1510,18 @@ def test_a_metric_that_computes_has_no_rejection() -> None: assert _http_workspace(_execute_handler()).execute_metric("m") is None +def test_a_maql_expression_is_executed_as_an_inline_measure() -> None: + bodies: list[dict] = [] + + def _handler(request: mw.httpx.Request) -> mw.httpx.Response: + if request.method == "POST": + bodies.append(json.loads(request.content)) + return _execute_handler()(request) + + assert _http_workspace(_handler).execute_maql("SELECT SUM({fact/x})") is None + assert bodies[0]["execution"]["measures"][0]["definition"] == {"inline": {"maql": "SELECT SUM({fact/x})"}} + + @pytest.mark.parametrize(("execute", "result"), [(400, 200), (200, 422)]) def test_a_platform_rejection_is_the_check_verdict(execute: int, result: int) -> None: reason = _http_workspace(_execute_handler(execute_status=execute, result_status=result)).execute_metric("m") diff --git a/packages/gooddata-eval/tests/test_sse_client.py b/packages/gooddata-eval/tests/test_sse_client.py index cd04c22b2..080e5ab54 100644 --- a/packages/gooddata-eval/tests/test_sse_client.py +++ b/packages/gooddata-eval/tests/test_sse_client.py @@ -116,6 +116,41 @@ def test_parse_sse_lines_stamps_call_and_result_receipt_time(monkeypatch): assert tc.index == 0 +def _tool_lines(*calls: tuple[str, str]) -> list[str]: + """SSE data lines for each (callId, name): the call, then its result.""" + lines = [] + for call_id, name in calls: + call = {"item": {"role": "assistant", "content": {"type": "toolCall", "callId": call_id, "name": name}}} + result = {"item": {"role": "tool", "content": {"type": "toolResult", "callId": call_id, "result": "{}"}}} + lines += [f"data: {json.dumps(call)}", "", f"data: {json.dumps(result)}", ""] + return lines + + +def test_the_tool_result_hook_sees_each_call_as_its_result_arrives() -> None: + order: list[str] = [] + result = parse_sse_lines( + _tool_lines(("c1", "create_metric"), ("c2", "search_objects")), + lambda event: order.append(f"{event['functionName']}:{event['result']}"), + ) + assert order == ["create_metric:{}", "search_objects:{}"] + assert [tc.result for tc in result.tool_call_events] == ["{}", "{}"] + + +def test_a_result_for_an_unknown_call_is_ignored_and_not_passed_to_the_hook() -> None: + result = {"item": {"role": "tool", "content": {"type": "toolResult", "callId": "nope", "result": "{}"}}} + seen: list[dict] = [] + parsed = parse_sse_lines([f"data: {json.dumps(result)}"], seen.append) + assert seen == [] and parsed.tool_call_events == [] + + +def test_send_message_passes_the_hook_to_the_stream() -> None: + body = "\n".join(_tool_lines(("c1", "create_metric"))).encode() + client = _client_with_handler(lambda request: httpx.Response(200, content=body)) + seen: list[dict] = [] + client.send_message("conv", "q", on_tool_result=seen.append) + assert [event["functionName"] for event in seen] == ["create_metric"] + + def test_build_latency_breakdown_gives_repeated_tool_calls_separate_entries_in_order(): # Same tool called twice, back-to-back (no gap between them). A dict keyed by tool # name would sum these into one number and lose which call was slower -- each call